很高兴您知道如何解决问题并继续学习教程!
我认为 Try F# 中代码片段的自动加载和评估有点令人困惑。问题是您首先评估第一个片段,它定义了Book
and unratedEdition
。然后,您评估重新定义的第二个片段Book
- 现在,对于 F# 交互式,这是一种隐藏先前定义的不同printRating
类型 - 以及在新版本的Book
. 你打电话时:
printRating unratedEdition
您正在调用printRating
which 是一个函数,它将带有旧类型的值的新 类型作为参数(因为是从早期的交互中定义的;它不会自动更新为新类型,并且这两种类型不兼容)。Book
Book
unratedEdition
Book
如果您对以下三个片段一一评估,您可以理解这一点:
// Snippet #1: Define first version of the 'Book' type and a value of
// this type named 'unratedEdition'
type Book =
{ Name: string; AuthorName: string; Rating: int option; ISBN: string }
let unratedEdition =
{ Name = "Expert F#"; Rating = None; ISBN = "1590598504";
AuthorName = "Don Syme, Adam Granicz, Antonio Cisternino"; }
// Snippet #2: Now, we re-define the 'Book' type (we could also add/remove
// fields to make it actually different, but even without that, this still
// defines a new type hiding the original one). We also define a function that
// operates on the new 'Book' type
type Book =
{ Name: string; AuthorName: string; Rating: int option; ISBN: string }
let printRating book =
match book.Rating with
| Some rating ->
printfn "I give this book %d star(s) out of 5!" rating
| None -> printfn "I didn't review this book"
// Snippet #3: This will not work, because we are calling function taking new
// 'Book' with old 'Book' as an argument. To make this work, you need to evaluate
// one (or the other) definition of Book, then evaluate 'unratedEdition' and then
// 'printRating' (so that the value and function operate on the same 'Book' type)
printRating unratedEdition
请注意,编辑器会抱怨上面的代码无效,因为它定义了Book
两次,所以你真的只能(很容易)在 Try F# 中遇到这个问题,它会在加载新片段时擦除编辑器的内容