F # - Syndicats discriminés

Les unions ou unions discriminées vous permettent de créer des structures de données complexes représentant un ensemble de choix bien défini. Par exemple, vous devez créer une implémentation d'une variable de choix , qui a deux valeurs oui et non. À l'aide de l'outil Unions, vous pouvez concevoir cela.

Syntaxe

Les unions discriminées sont définies à l'aide de la syntaxe suivante -

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

Notre implémentation simple de, choice, ressemblera à ce qui suit -

type choice =
   | Yes
   | No

L'exemple suivant utilise le choix de type -

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()

Lorsque vous compilez et exécutez le programme, il produit la sortie suivante -

x: Yes
y: No

Exemple 1

L'exemple suivant montre l'implémentation des états de tension qui définissent un bit sur haut ou bas -

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()

Lorsque vous compilez et exécutez le programme, il produit la sortie suivante -

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

Exemple 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)

Lorsque vous compilez et exécutez le programme, il produit la sortie suivante -

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