82 people like it.

Chain of responsibility

The following sample wants to make sure the person’s age is between 18 and 65, weight is no more than 200 and tall enough (>120).

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
type Record = {
    Name : string;
    Age : int;
    Weight: float;
    Height: float;
}

let ChainOfResponsibility() = 
    let validAge (record:Record) = 
        record.Age < 65 && record.Age > 18
    let validWeight (record:Record) = 
        record.Weight < 200.
    let validHeight (record:Record) = 
        record.Height > 120.

    let check (f:Record->bool) (record:Record, result:bool) = 
        if result=false then (record, false)
        else (record, f(record))

    let chainOfResponsibility = check(validAge) >> check(validWeight) >> check(validHeight)

    let john = { Name = "John"; Age = 80; Weight = 180.; Height=180. }
    let dan = { Name = "Dan"; Age = 20; Weight = 160.; Height=190. }

    printfn "john result = %b" ((chainOfResponsibility (john, true)) |> snd)
    printfn "dan result = %b" ((chainOfResponsibility (dan, true)) |> snd)
Record.Name: string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
Record.Age: int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
Record.Weight: float
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
Record.Height: float
val ChainOfResponsibility : unit -> unit

Full name: Script.ChainOfResponsibility
val validAge : (Record -> bool)
val record : Record
type Record =
  {Name: string;
   Age: int;
   Weight: float;
   Height: float;}

Full name: Script.Record
val validWeight : (Record -> bool)
val validHeight : (Record -> bool)
val check : ((Record -> bool) -> Record * bool -> Record * bool)
val f : (Record -> bool)
type bool = System.Boolean

Full name: Microsoft.FSharp.Core.bool
val result : bool
val chainOfResponsibility : (Record * bool -> Record * bool)
val john : Record
val dan : Record
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val snd : tuple:('T1 * 'T2) -> 'T2

Full name: Microsoft.FSharp.Core.Operators.snd
Raw view Test code New version

More information

Link:http://fssnip.net/7h
Posted:12 years ago
Author:Tao Liu
Tags: design patterns