我有以下代码
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. 我做错了什么?
发布于 2015-03-05 15:07:00
同一问题有两个实例。在定义函数时,将:*type*放在签名的末尾表示函数返回该类型。在本例中,您指示您有一个函数f2,它接受一个参数并返回一个int。要修复它,需要在注释周围加上括号。这个语法在lambda中不起作用,所以您只需得到一个编译错误。
发布于 2015-03-05 15:05:56
您必须在类型注释周围加上括号:
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#中这将是什么:
ReturnTypeOfFunction functionName(TypeOfParam1 firstParam, TypeOfParam2 secondParam) { ... }在F#中如下所示:
let functionName (firstParam : TypeOfParam1) (secondParam : TypeOfParam2) : ReturnTypeOfFunction =
// Function implementation that returns object of type ReturnTypeOfFunction更详细的解释可以找到论MSDN。
发布于 2015-03-05 15:06:47
或者让编译器推断类型。试试这个:
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" https://stackoverflow.com/questions/28880934
复制相似问题