When to use `let ... in` to bind variables?

时间:2017-12-18 07:23:22

标签: .net f# functional-programming

Based on the anwser of "Meaning of keyword “in” in F#":

let (x = 2 and y = x + 2) in
    y + x

This will not work the same as

let (x = 2 and y = x + 2)
    y + x

In the former case x is only bound after the in keyword. In the later case normal variable scoping rules take effect, so variables are bound as soon as they are declared.

When one need to specify bound variables with in, instead of binding as they are declared?

1 个答案:

答案 0 :(得分:4)

您可以像这样使用let / in

let x = 2 in
    let y = x + 2 in
        y + x

F#是一种基于表达式的语言,这种形式的代码揭示了这一点。然而,内置了语法糖,因此您可以以平面方式编写相同的内容,看起来基于语句,但实际上并非如此:

let x = 2
let y = x + 2
y + x

如果您真的想要留在同一行in,可以使用let x = 2 in x + 2。但是,看到这一点非常不寻常。在成千上万的F#系列中,我曾与我合作过,从未见过或自己使用过它。