3 people like it.

Functional Argument Accumulator

Applicative style argument accumulator functions inspired by the FParsec.Pipes library. It works by weaving a single continuation argument like a chain, kind of like the pipe function of FParsec but with a arbitrary number of arguments.

 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: 
// Argument accumulator inspired by FParsec.Pipes
    
type Result<'a,'b> = Succ of 'b | Fail of 'a

let either f s = function
    | Succ x -> s x
    | Fail x -> f x

let (|?>) x f = either Fail f x

let a = Succ "asd"
let b = Succ 2
let c = Succ 'a'

let start a = 
    match a with
    | Succ a -> (fun k -> k a) |> Succ
    | Fail x -> Fail x

let next b a = 
    match a with
    | Succ a ->
        match b with
        | Succ b -> a |> (fun x k -> x k b) |> Succ
        | Fail x -> Fail x
    | Fail x -> Fail x

let fin k a =
    match a with
    | Succ a -> Succ <| a k
    | Fail x -> Fail x

let r: Result<string,_> = 
    start a |> next b |> next c
    |> fin (fun a b c -> c)
union case Result.Succ: 'b -> Result<'a,'b>
union case Result.Fail: 'a -> Result<'a,'b>
val either : f:('a -> 'b) -> s:('c -> 'b) -> _arg1:Result<'a,'c> -> 'b

Full name: Script.either
val f : ('a -> 'b)
val s : ('c -> 'b)
val x : 'c
val x : 'a
val x : Result<'a,'b>
val f : ('b -> Result<'a,'c>)
val a : Result<'a,string>

Full name: Script.a
val b : Result<'a,int>

Full name: Script.b
val c : Result<'a,char>

Full name: Script.c
val start : a:Result<'a,'b> -> Result<'a,(('b -> 'c) -> 'c)>

Full name: Script.start
val a : Result<'a,'b>
val a : 'b
val k : ('b -> 'c)
val next : b:Result<'a,'b> -> a:Result<'a,('c -> 'b -> 'd)> -> Result<'a,('c -> 'd)>

Full name: Script.next
val b : Result<'a,'b>
val a : Result<'a,('c -> 'b -> 'd)>
val a : ('c -> 'b -> 'd)
val b : 'b
val x : ('c -> 'b -> 'd)
val k : 'c
val fin : k:'a -> a:Result<'b,('a -> 'c)> -> Result<'b,'c>

Full name: Script.fin
val k : 'a
val a : Result<'b,('a -> 'c)>
val a : ('a -> 'c)
val x : 'b
val r : Result<string,char>

Full name: Script.r
type Result<'a,'b> =
  | Succ of 'b
  | Fail of 'a

Full name: Script.Result<_,_>
Multiple items
val string : value:'T -> string

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

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

Full name: Microsoft.FSharp.Core.string
val a : string
val b : int
val c : char

More information

Link:http://fssnip.net/7Sd
Posted:4 months ago
Author:Marko Grdinić
Tags: combinators , continuation