Last active
August 29, 2015 14:04
-
-
Save dvdsgl/eac75ee61a811ce72764 to your computer and use it in GitHub Desktop.
Implement Writer monad with custom keyword.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Writer<'Result, 'Output> = | |
| W of 'Result * seq<'Output> | |
type WriterBuilder() = | |
member this.Zero() = W ((), Seq.empty) | |
member this.Yield(x) = W (x, Seq.empty) | |
member this.Return(x) = this.Yield(x) | |
member this.Bind(W (a, xs), k) = | |
let (W (b, ys)) = k a | |
W (b, Seq.append xs ys) | |
[<CustomOperation("write", MaintainsVariableSpace=true)>] | |
member this.Write(W (a, xs), x) = | |
W (a, Seq.append xs (Seq.singleton x)) | |
let writer = WriterBuilder() | |
let logger = writer { | |
write "Hello" | |
write "World" | |
write "David" | |
} | |
let runWriter (W (a, xs)) = xs | |
[<EntryPoint>] | |
let main argv = | |
printfn "Wrote out: %A" (runWriter logger) | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment