FSharp 参数模式匹配。为什么声明分配自而不是分配给?

FSharp Parameter Pattern matching. Why is declaration assigned from instead of to?

我在看FSharp。 目前我正在阅读这个资源: http://fsharpforfunandprofit.com/

由于我正在学习一些全新的东西,包括一种新的思维方式,所以我很小心地让一些对我来说意义不大的东西溜走。

let f1 name =                        // pass in single parameter   
    let {first=f; last=l} = name     // extract in body of function 
    printfn "first=%s; last=%s" f l

为什么 "f" 和 "l" 在各自“=”符号的 右边 一侧?这不是宣布他们的时候吗?我相信我知道 该行的作用(它从 "name" 记录中提取 "first" 和 "last" 属性)。但是我无法理解这种语法选择背后的原因,这让我怀疑我并不真正理解这里发生的全部事情。

let= 之间的语法部分称为 pattern。如评论中所述,该模式反映了您在创建记录时使用的语法。

更一般地说,模式的想法是您指定您知道的对象部分(此处为记录字段名称),并且在变化的地方(字段的值),您可以将变量名(在这种情况下,模式匹配 绑定 一个变量)或者你可以写 _ 来忽略对象那部分的值。

以下是一些创造价值的例子:

let opt = Some(42)                              // Option type containing int
let rcd = { First = "Tomas"; Last = "Hidden" }  // Record from your example
let tup = 42, "Hello"                           // Tuple with int and string

在所有情况下,您都可以在模式中镜像语法:

let (Some(num)) = opt         // This gives warning, because 'opt' could also be None
let { First = n; Last = _ }   // Here, we explicitly ignore the last name using '_'
let _, str = tup              // Ignore first component of the tuple, but get the 2nd