0 people like it.

Fold functions over static values builder 2

Now with nice syntax!

 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: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
open System.Collections.Generic
open System.Runtime.CompilerServices

type Folder<'State, 'T> = 'State -> 'T -> 'State
type FoldParams<'State, 'T> = Folder<'State, 'T> * 'State
type FoldStep<'State, 'T> = ('State -> 'T -> 'State) -> 'State -> 'State

[<Extension>]
type Ext =
    [<Extension>]
    static member Zero(_: FoldParams<'State, 'T>): FoldStep<'State, 'T> = 
        fun _ state -> state
    
    [<Extension>]
    static member inline Combine(
        (folder: Folder<'State, 'T>, _: 'State),
        [<InlineIfLambda>] f: FoldStep<'State, 'T>, 
        [<InlineIfLambda>] g: FoldStep<'State, 'T>)
        : FoldStep<'State, 'T> =
        fun folder state -> g folder (f folder state)
    
    [<Extension>]
    static member inline Delay(
        _: FoldParams<'State, 'T>,
        [<InlineIfLambda>] f: unit -> FoldStep<'State, 'T>) = 
        f()
    
    [<Extension>]
    static member inline Yield(
        (folder: Folder<'State, 'T>, _: 'State),
        value: 'T)
        : FoldStep<'State, 'T> = 
        fun folder state -> folder state value
    
    [<Extension>]
    static member inline Run(
        (folder: Folder<'State, 'T>, initialState: 'State),
        f: FoldStep<'State, 'T>) =
        f folder initialState

let fold' folder initialState = (folder, initialState)
let f = fold' (+) 0 { 1; 2; 3; 4; 5 }
printfn "%d" f
namespace System
namespace System.Collections
namespace System.Collections.Generic
namespace System.Runtime
namespace System.Runtime.CompilerServices
type Folder<'State,'T> = 'State -> 'T -> 'State
type FoldParams<'State,'T> = Folder<'State,'T> * 'State
type FoldStep<'State,'T> = ('State -> 'T -> 'State) -> 'State -> 'State
Multiple items
type ExtensionAttribute =
  inherit Attribute
  new : unit -> ExtensionAttribute

--------------------
ExtensionAttribute() : ExtensionAttribute
val state : 'State
val folder : Folder<'State,'T>
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 initialState : 'State
val fold' : folder:'a -> initialState:'b -> 'a * 'b
val folder : 'a
val initialState : 'b
val f : int
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Raw view Test code New version

More information

Link:http://fssnip.net/85V
Posted:2 years ago
Author:Evgeniy Andreev
Tags: herp , derp