Das funktioniert teilweise auch mit F# Union Type.
Die Signaturdatei mit verdeckten Resistor Konstruktoren.
//Resistor.fsi
namespace SmartConstructors
module Resistor =
type Bands = int
// Union Type with hiding constructors
type Resistor = private Metal of Bands | Ceramic of Bands
//smart constructor.
val metalResistor : Bands -> Resistor
val (|Metal|Ceramic|) : Resistor -> Choice<Bands,Bands>
Implementierung. //Resistor.fs
namespace SmartConstructors
open System
module Resistor =
type Bands = int
type Resistor = Metal of Bands | Ceramic of Bands with
override x.ToString()=
match x with
| (Metal v) -> "Metal " + v.ToString()
| (Ceramic v) -> "Ceramic " + v.ToString()
//smart constructor.
let metalResistor (b:Bands) =
assert ( b >= 4 && b <= 8)
Metal b
let (|Metal|Ceramic|) n =
match n with
| (Metal v) -> Metal v
| (Ceramic v) -> Ceramic v
Aufrufen. // other F# Console Project
// with reference to SmartConstructors.dll
// Program.fs
open SmartConstructors.Resistor
//don't compile
//let failResistor = Metal 5
//only way to build a metal resistor
let resistor6 = metalResistor 6
let getBands r =
match r with
| Metal v -> v
| Ceramic v -> v
printfn "%A" (resistor6.ToString())
printfn "%A" (getBands resistor6)
//Assertion failed
let resistor10 = metalResistor 10
printfn "%A" (resistor10.ToString())
Keine Kommentare:
Kommentar veröffentlichen