Skip to content

Instantly share code, notes, and snippets.

@markhibberd
Last active December 12, 2015 03:59
Show Gist options
  • Select an option

  • Save markhibberd/4711123 to your computer and use it in GitHub Desktop.

Select an option

Save markhibberd/4711123 to your computer and use it in GitHub Desktop.
Implement terminating operation on (Boolean, A).
case class X[A](ok: Boolean, value: A) {
def map[B](f: A => B): X[B] =
X(ok, f(a))
def flatMap[B](f: A => X[B]) X[B] =
f(value)
def thenOr[B](f: A => X[B], otherwise: A => B) =
if (ok) then flatMap(f) else map(otherwise)
}
object XClient {
val x = for {
a <- X(true, 1) // will continue no matter value of ok
b <- X(false, "asf") // will continue no matter value of ok
c <- X(true, a).thenOr(_ => X(true, "something"), _ => "else") // c will be something
d <- X(false, a).thenOr(_ => X(true, "something"), _ => "else") // d will be else
} yield z
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment