次の方法で共有


ラムダ式: fun キーワード (F#)

fun キーワードは、ラムダ式、つまり匿名関数を定義するために使用されます。

構文

fun parameter-list -> expression

または、 _.Property の短縮表記を使用します。

_.

funparameter-list、ラムダ矢印 (->) は省略され、_.は、パラメーターシンボル_置き換えるの一部です。

次のスニペットは同等です。

(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] -> …

は関数の本体であり、最後の式は戻り値を生成します。 有効なラムダ式の例を次に示します。

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)

ラムダ式の使用

ラムダ式は、リストまたはその他のコレクションに対して操作を実行し、関数を定義する余分な作業を回避する場合に特に便利です。 多くの F# ライブラリ関数は関数値を引数として受け取ります。このような場合はラムダ式を使用すると特に便利です。 次のコードでは、ラムダ式をリストの要素に適用します。 この場合、匿名関数は、要素が指定した文字で終わるテキストであるかどうかを確認します。

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 表記の両方の表記を示しています。

こちらも参照ください