Fsharp-options

提供:Dev Guides
移動先:案内検索

F#-オプション

F#の option タイプは、変数または関数の値が存在する場合と存在しない場合の計算で使用されます。 オプションタイプは、計算でオプション値を表すために使用されます。 * Some(x)または *None の2つの値を設定できます。

たとえば、除算を実行する関数は、通常の状況では値を返しますが、分母がゼロの場合は例外をスローします。 ここでオプションを使用すると、関数が成功したか失敗したかを示すのに役立ちます。

オプションには基礎となるタイプがあり、そのタイプの値を保持できますが、値がない場合もあります。

オプションを使用する

除算関数の例を見てみましょう。 次のプログラムはこれを説明します-

関数divを書いて、20と5に2つの引数を送りましょう-

let div x y = x/y
let res = div 20 5
printfn "Result: %d" res

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

Result: 4

2番目の引数がゼロの場合、プログラムは例外をスローします-

let div x y = x/y
let res = div 20 0
printfn "Result: %d" res

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

Unhandled Exception:
System.DivideByZeroException: Division by zero

このような場合、オプションタイプを使用して、操作が成功した場合はSome(値)を返し、操作が失敗した場合はNoneを返すことができます。

次の例は、オプションの使用を示しています-

let div x y =
   match y with
   | 0 -> None
   | _ -> Some(x/y)

let res : int option = div 20 4
printfn "Result: %A " res

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

Result: Some 5

オプションのプロパティとメソッド

オプションタイプは、次のプロパティとメソッドをサポートしています-

Property or method Type Description
None 'T option A static property that enables you to create an option value that has the None value.
IsNone bool Returns true *if the option has the None *value.
IsSome bool Returns* true if the option has a value that is not None*.
Some 'T option A static member that creates an option that has a value that is not None.
Value 'T Returns the underlying value, or throws a NullReferenceException if the value is None.

例1

let checkPositive (a : int) =
   if a > 0 then
      Some(a)
   else
      None

let res : int option = checkPositive(-31)
printfn "Result: %A " res

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

Result: <null>

例2

let div x y =
   match y with
   | 0 -> None
   | _ -> Some(x/y)

let res : int option = div 20 4
printfn "Result: %A " res
printfn "Result: %A " res.Value

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

Result: Some 5
Result: 5

実施例3

let isHundred = function
   | Some(100) -> true
   | Some(_) | None -> false

printfn "%A" (isHundred (Some(45)))
printfn "%A" (isHundred (Some(100)))
printfn "%A" (isHundred None)

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

false
true
false