简单的闭包函数

zer*_*ing 0 f#

我有以下代码

let f2 x:int = 
    fun s:string ->
        match x with
        | x when x > 0 -> printfn "%s" s
        | _ -> printfn "%s" "Please give me a number that is greater than 0" 
Run Code Online (Sandbox Code Playgroud)

编译器抱怨:

Unexpected symbol ':' in lambda expression. Expected '->' or other token. 
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Nik*_*ird 5

您必须在类型注释两边加上括号:

let f2 (x : int) = 
    fun (s : string) ->
        match x with
        | x when x > 0 -> printfn "%s" s
        | _ -> printfn "%s" "Please give me a number that is greater than 0" 
Run Code Online (Sandbox Code Playgroud)

另请注意,如果像示例中那样省略括号x,则这意味着该函数f2返回 int,而不是将其类型限制x为 int。


评论更新:

为什么如果我省略 x 两边的括号,这意味着函数 f2 返回一个 int ?

因为这就是指定函数返回类型的方式。

在 C# 中这会是什么:

ReturnTypeOfFunction functionName(TypeOfParam1 firstParam, TypeOfParam2 secondParam) { ... }
Run Code Online (Sandbox Code Playgroud)

在 F# 中看起来像这样:

let functionName (firstParam : TypeOfParam1) (secondParam : TypeOfParam2) : ReturnTypeOfFunction =
    // Function implementation that returns object of type ReturnTypeOfFunction
Run Code Online (Sandbox Code Playgroud)

更详细的解释可以在MSDN上找到。