36 people like it.
Like the snippet!
Decorate pattern
implement the decorate pattern in F#. The decorate pattern is to add new featuures to an object at runtime.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
|
type Divide() =
let mutable divide = fun (a,b) -> a / b
member this.Function
with get() = divide
and set(v) = divide <- v
member this.Invoke(a,b) = divide (a,b)
let decorate() =
let d = Divide()
let checkZero (a,b) = if b = 0 then failwith "a/b and b is 0" else (a,b)
try
d.Invoke(1, 0) |> ignore
with e -> printfn "without check, the error is = %s" e.Message
d.Function <- checkZero >> d.Function
try
d.Invoke(1,0) |> ignore
with e -> printfn "after add check, error is = %s" e.Message
|
Multiple items
type Divide =
new : unit -> Divide
member Invoke : a:int * b:int -> int
member Function : (int * int -> int)
member Function : (int * int -> int) with set
Full name: Script.Divide
--------------------
new : unit -> Divide
val mutable divide : (int * int -> int)
val a : int
val b : int
val this : Divide
member Divide.Function : (int * int -> int) with set
Full name: Script.Divide.Function
val set : elements:seq<'T> -> Set<'T> (requires comparison)
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.set
val v : (int * int -> int)
member Divide.Invoke : a:int * b:int -> int
Full name: Script.Divide.Invoke
val decorate : unit -> unit
Full name: Script.decorate
val d : Divide
val checkZero : ('a * int -> 'a * int)
val a : 'a
val failwith : message:string -> 'T
Full name: Microsoft.FSharp.Core.Operators.failwith
member Divide.Invoke : a:int * b:int -> int
val ignore : value:'T -> unit
Full name: Microsoft.FSharp.Core.Operators.ignore
val e : exn
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
property System.Exception.Message: string
property Divide.Function: int * int -> int
More information