1 people like it.

Fold functions over static values builder

Fold it!

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
type FoldStep<'State, 'T> = ('State -> 'T -> 'State) -> 'State -> 'State

type FoldBuilder() =
    member this.Zero(): FoldStep<'State, 'T> = 
        fun _ state -> state
    
    member inline this.Combine(
        [<InlineIfLambda>] f: FoldStep<'State, 'T>, 
        [<InlineIfLambda>] g: FoldStep<'State, 'T>)
        : FoldStep<'State, 'T> =
        fun folder state -> g folder (f folder state)
    
    member inline this.Delay([<InlineIfLambda>] f: unit -> FoldStep<'State, 'T>) = 
        f()
    
    member inline this.Yield(value: 'T): FoldStep<'State, 'T> = 
        fun folder state -> folder state value
    
let fold = FoldBuilder()

let f = (fold { 1; 2; 3; 4; 5 }) (+) 0
printfn "%d" f
Multiple items
type FoldBuilder =
  new : unit -> FoldBuilder
  member Combine : f:FoldStep<'State,'T> * g:FoldStep<'State,'T> -> FoldStep<'State,'T>
  member Delay : f:(unit -> FoldStep<'State,'T>) -> FoldStep<'State,'T>
  member Yield : value:'T -> FoldStep<'State,'T>
  member Zero : unit -> FoldStep<'State,'T>

--------------------
new : unit -> FoldBuilder
val this : FoldBuilder
type FoldStep<'State,'T> = ('State -> 'T -> 'State) -> 'State -> 'State
val state : 'State
val f : FoldStep<'State,'T>
val g : FoldStep<'State,'T>
val folder : ('State -> 'T -> 'State)
val f : (unit -> FoldStep<'State,'T>)
type unit = Unit
val value : 'T
val fold : FoldBuilder
val f : int
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Raw view Test code New version

More information

Link:http://fssnip.net/85U
Posted:8 months ago
Author:Evgeniy Andreev
Tags: computation builder , computation expressions , fold