F# 简单闭包函数

F# 简单闭包函数,f#,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" 而编译器则抱怨: Unexpected symbol ':' in lambda expression. E

我有以下代码

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" 
而编译器则抱怨:

Unexpected symbol ':' in lambda expression. Expected '->' or other token. 

我做错了什么?

您必须在类型批注周围加上括号:

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" 
还要注意,如果您像在示例中那样省略了
x
周围的括号,这意味着函数
f2
返回一个int,而不是将
x
的类型限制为int


最新评论:


为什么如果省略x周围的括号,这意味着函数f2返回int

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

这在C#中是什么

在F#中是这样的:


可以找到更详细的解释。

或者让编译器推断类型。试试这个:

let f2 x = 
    fun s ->
        match x with
        | x when x > 0 -> printfn "%s" s
        | _ -> printfn "%s" "Please give me a number that is greater than 0" 

您有两个相同问题的实例。定义函数时,将
:*type*
放在签名的末尾表示函数返回该类型。在本例中,您表示有一个函数
f2
,它接受一个参数并返回一个
int
。要修复它,需要在注释周围加上括号。这种语法在lambda中不起作用,因此只会得到一个编译错误。

为什么如果省略x周围的括号,这意味着函数f2返回int?
let functionName (firstParam : TypeOfParam1) (secondParam : TypeOfParam2) : ReturnTypeOfFunction =
    // Function implementation that returns object of type ReturnTypeOfFunction
let f2 x = 
    fun s ->
        match x with
        | x when x > 0 -> printfn "%s" s
        | _ -> printfn "%s" "Please give me a number that is greater than 0"