Created
October 4, 2011 19:27
-
-
Save missingfaktor/1262539 to your computer and use it in GitHub Desktop.
Either monad
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
| scala> def unsafe[A](f: => A): Either[Throwable, A] = try Right(f) catch { case x => Left(x) } | |
| unsafe: [A](f: => A)Either[Throwable,A] | |
| scala> def A(x: Int) = x + 10 | |
| A: (x: Int)Int | |
| scala> def B(x: Int) = x.toString | |
| B: (x: Int)java.lang.String | |
| scala> def C(s: String) = s + "!" | |
| C: (s: String)java.lang.String | |
| scala> def D(s: String) = "Doh" | |
| D: (s: String)java.lang.String | |
| scala> def KaPow(s: String): String = sys.error("Ka Pow!") | |
| KaPow: (s: String)String | |
| scala> def result(i: Int) = for { | |
| | a <- unsafe(A(i)) | |
| | b <- unsafe(B(a)) | |
| | k <- unsafe(KaPow(b)) | |
| | c <- unsafe(C(k)) | |
| | } yield D(c) | |
| result: (i: Int)Either[Throwable,java.lang.String] | |
| scala> result(9) | |
| res32: Either[Throwable,java.lang.String] = Left(java.lang.RuntimeException: Ka Pow!) | |
| scala> def result(i: Int) = for { | |
| | a <- unsafe(A(i)) | |
| | b <- unsafe(B(a)) | |
| | c <- unsafe(C(b)) | |
| | } yield D(c) | |
| result: (i: Int)Either[Throwable,java.lang.String] | |
| scala> result(9) | |
| res33: Either[Throwable,java.lang.String] = Right(Doh) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment