Lambda 運算式:fun 關鍵字 (F#)

fun 關鍵字可用來定義 Lambda 運算式,這是一個匿名函式。

語法

fun parameter-list -> expression

備註

「參數清單」通常包含名稱和選擇性參數類型。 更概括來說,「參數清單」可以由任何 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 運算式套用至清單的元素。 在此案例中,匿名函式會將 1 新增至清單的每個元素。

let list = List.map (fun i -> i + 1) [ 1; 2; 3 ]
printfn "%A" list

另請參閱