关键字 fun
用于定义 lambda 表达式,即匿名函数。
语法
fun parameter-list -> expression
_.Property
或使用速记表示法:
_.
fun
省略 参数列表和 lambda 箭头(->
),并且 _.
是 表达式 的一部分,用于 _
替换参数符号。
以下代码片段等效:
(fun x -> x.Property)
_.Property
注解
参数列表通常由名称和(可选)参数类型组成。 更通常, 参数列表 可以由任何 F# 模式组成。 有关可能模式的完整列表,请参阅 模式匹配。 有效参数列表包括以下示例。
// Lambda expressions with parameter lists.
fun a b c -> ...
fun (a: int) b c -> ...
fun (a : int) (b : string) (c:float) -> ...
// A lambda expression with a tuple pattern.
fun (a, b) -> …
// A lambda expression with a cons pattern.
// (note that this will generate an incomplete pattern match warning)
fun (head :: tail) -> …
// A lambda expression with a list pattern.
// (note that this will generate an incomplete pattern match warning)
fun [_; rest] -> …
表达式是函数的主体,最后一个表达式将生成返回值。 有效 lambda 表达式的示例包括:
fun x -> x + 1
fun a b c -> printfn "%A %A %A" a b c
fun (a: int) (b: int) (c: int) -> a + b * c
fun x y -> let swap (a, b) = (b, a) in swap (x, y)
使用 Lambda 表达式
如果要对列表或其他集合执行作,并且希望避免定义函数的额外工作,Lambda 表达式特别有用。 许多 F# 库函数采用函数值作为参数,在这些情况下使用 lambda 表达式尤其方便。 以下代码将 lambda 表达式应用于列表的元素。 在这种情况下,匿名函数将检查元素是否为以指定字符结尾的文本。
let fullNotation = [ "a"; "ab"; "abc" ] |> List.find ( fun text -> text.EndsWith("c") )
printfn "%A" fullNotation // Output: "abc"
let shorthandNotation = [ "a"; "ab"; "abc" ] |> List.find ( _.EndsWith("b") )
printfn "%A" shorthandNotation // Output: "ab"
前面的代码片段显示了两种表示法:使用 fun
关键字和速记 _.Property
表示法。