Skip to content

Instantly share code, notes, and snippets.

@Ball
Created November 19, 2012 20:58
Show Gist options
  • Save Ball/4113838 to your computer and use it in GitHub Desktop.
Save Ball/4113838 to your computer and use it in GitHub Desktop.
Learning Monads - Stack from the javascript example
// Adapted from http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html
type StackResult = {value: int; stack: int list}
let push element stack =
{value= element; stack = element :: stack}
let pop stack =
{value= (List.head stack); stack = (List.tail stack)}
let bind operation continuation stack =
let r = operation stack
let newStack = r.stack
continuation (r.value) r.stack
let result value stack = {value = value; stack = stack}
type StackBuilder() =
member this.Bind(x, f) = bind x f
member this.Delay(f) = f()
member this.Return(x) = result x
let stackExpression = new StackBuilder()
let comp = bind (push 4) (fun r0 ->
bind (push 5) (fun r1 ->
bind (pop) (fun r2 ->
bind (pop) (fun r3 ->
result (r2 + r3)
)
)
)
)
let cmp = stackExpression {
let! _ = push 4
let! _ = push 5
let! a = pop
let! b = pop
return a + b
}
printfn "comp -- %d" (comp []).value
printfn "cmp -- %d" (cmp []).value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment