Fsharp-discriminated-unions

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

F#-差別された組合

ユニオン、または差別化されたユニオンにより、明確に定義された選択肢セットを表す複雑なデータ構造を構築できます。 たとえば、yesとnoの2つの値を持つ_choice_変数の実装を構築する必要があります。 Unionsツールを使用して、これを設計できます。

構文

差別化された労働組合は、次の構文を使用して定義されています-

type type-name =
   | case-identifier1 [of [ fieldname1 : ] type1 [ *[ fieldname2 : ]
type2 ...]
   | case-identifier2 [of [fieldname3 : ]type3 [* [ fieldname4 : ]type4 ...]
...

、_choice、_の簡単な実装は次のようになります-

type choice =
   | Yes
   | No

次の例では、タイプの選択を使用します-

type choice =
   | Yes
   | No

let x = Yes ( *creates an instance of choice* )
let y = No ( *creates another instance of choice* )
let main() =
   printfn "x: %A" x
   printfn "y: %A" y
main()

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

x: Yes
y: No

例1

次の例は、高または低にビットを設定する電圧状態の実装を示しています-

type VoltageState =
   | High
   | Low

let toggleSwitch = function ( *pattern matching input* )
   | High -> Low
   | Low -> High

let main() =
   let on = High
   let off = Low
   let change = toggleSwitch off

   printfn "Switch on state: %A" on
   printfn "Switch off state: %A" off
   printfn "Toggle off: %A" change
   printfn "Toggle the Changed state: %A" (toggleSwitch change)

main()

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

Switch on state: High
Switch off state: Low
Toggle off: High
Toggle the Changed state: Low

例2

type Shape =
  //here we store the radius of a circle
   | Circle of float

  //here we store the side length.
   | Square of float

  //here we store the height and width.
   | Rectangle of float *float

let pi = 3.141592654

let area myShape =
   match myShape with
   | Circle radius -> pi* radius *radius
   | Square s -> s* s
   | Rectangle (h, w) -> h * w

let radius = 12.0
let myCircle = Circle(radius)
printfn "Area of circle with radius %g: %g" radius (area myCircle)

let side = 15.0
let mySquare = Square(side)
printfn "Area of square that has side %g: %g" side (area mySquare)

let height, width = 5.0, 8.0
let myRectangle = Rectangle(height, width)
printfn "Area of rectangle with height %g and width %g is %g" height width (area myRectangle)

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

Area of circle with radius 12: 452.389
Area of square that has side 15: 225
Area of rectangle with height 5 and width 8 is 40