關鍵詞 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 表示法。