Skip to content

Instantly share code, notes, and snippets.

@lasandell
Last active August 29, 2015 14:23
Show Gist options
  • Save lasandell/129a6f123335164db0fa to your computer and use it in GitHub Desktop.
Save lasandell/129a6f123335164db0fa to your computer and use it in GitHub Desktop.
F# Ping Pong Computation Expression!
// State types
type Ping = Ping
type Pong = Pong
// Builder that requires every "ping" to be
// immediately answered by a "pong"
type PingBuilder() =
member __.Yield(()) = Pong
member __.Run(Pong) = ()
[<CustomOperation("ping")>]
member __.Ping(Pong) = Ping
[<CustomOperation("pong")>]
member __.Pong(Ping) = Pong
let ping = PingBuilder()
// Compiles - balanced
ping {
ping
pong
ping
pong
}
// Doesn't compile - not balanced
ping {
ping
pong
ping
}
// Builder that requires every "ping" to be
// eventually answered by a "pong"
type PongBuilder() =
member __.Yield(()) = ()
member __.Run(()) = ()
[<CustomOperation("ping")>]
member __.Ping(rest) = Ping, rest
[<CustomOperation("pong")>]
member __.Pong((Ping, rest)) = rest
let pong = PongBuilder()
// Compiles - balanced
pong {
ping
ping
pong
ping
pong
pong
}
// Doesn't compile - not balanced
pong {
ping
ping
pong
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment