F#には、このようなものはそのままではありません。主な理由は、F#は静的に型指定された言語であり、同様のパターンをサポートするのが難しいためです(リストには、1つの型の値のみが含まれる場合がありますが、関数には異なるパラメーターが含まれる場合があります)。
リンクされた回答で述べたように、リフレクションを使用して同様のアイデアをエミュレートできます。これは遅くて安全ではありませんが、これを行う正当な理由がある場合は、試してみてください。
前の回答の関数といくつかのアクティブなパターンを使用してtupleToList
、次のように書くことができます。
// Converts any F# tuple to a list of objects using reflection
let tupleToList t =
if Microsoft.FSharp.Reflection.FSharpType.IsTuple(t.GetType())
then Some (Microsoft.FSharp.Reflection.FSharpValue.GetTupleFields t |> Array.toList)
else None
// Active pattern that accepts any object and extracts its members
// if it is a tuple or a sequence of values (e.g. list)
let (|Arguments|_|) (a:obj) =
match a, tupleToList a with
| _, Some t -> Some t
| :? System.Collections.IEnumerable as l, _ ->
l |> Seq.cast |> List.ofSeq |> Some
| _ -> None
// Treat the argument as an int (this may fail)
let (|Int|_|) (a:obj) = match a with :? int as n -> Some n | _ -> None
// Function that assumes to get three integers
let f (Arguments [Int a;Int b;Int c]) =
printfn "%d" (a + b + c)
f (1, 2, 3) // Call with tuple
f [1;2;3] // Call with a list
f (1, "hi", 3, 141.1) // This will fail at runtime, but compiler allows it :-(
これはおそらくあまり慣用的なF#ではなく、回避しようとしますが、うまくいく可能性があります。