Skip to content

Instantly share code, notes, and snippets.

@krasserm
Created January 1, 2011 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krasserm/761878 to your computer and use it in GitHub Desktop.
Save krasserm/761878 to your computer and use it in GitHub Desktop.
import scalaz._
object Example extends Application {
import Scalaz._
import Scalaz._
//
// monadic use of Either
//
// use of type lambdas (see http://groups.google.com/group/scalaz/browse_thread/thread/862543e872b09f3c)
type ES[α] = ({type λ[α] = Either[String, α]})#λ[α]
// alternatively use the old PartialApply1Of2 notation
//type ES[B] = PartialApply1Of2[Either, String]#Apply[B]
type P = String => Either[String, String]
// create a Kleisli structure from monadic function p for being composable with >=>
implicit def k(p: P) = kleisli[ES, String, String](p)
val f: P = (s: String) => (s + "1").right
val g: P = (s: String) => ("wrong").left
val h: P = (s: String) => (s + "2").right
// all computations succeed
f >=> h apply "a" assert_≟ Right("a12")
// first computation fails
g >=> h apply "a" assert_≟ Left("wrong")
//
// applicative use of Either
//
val a: Either[String, Int] = 1.right
val b: Either[String, Int] = 1.right
val c: Either[String, Int] = "error".left
val d: Either[String, Int] = "wrong".left
(a <**> b){_ + _} assert_≟ Right(2)
(c <**> b){_ + _} assert_≟ Left("error")
(c <**> d){_ + _} assert_≟ Left("error")
(d <**> c){_ + _} assert_≟ Left("wrong")
//
// applicative use of Validation
//
val v: Validation[String, Int] = 1.success
val w: Validation[String, Int] = 1.success
val x: Validation[String, Int] = "error".fail
val y: Validation[String, Int] = "wrong".fail
(v <**> w){_ + _} assert_≟ Success(2)
(x <**> w){_ + _} assert_≟ Failure("error")
(x <**> y){_ + _} assert_≟ Failure("errorwrong")
(y <**> x){_ + _} assert_≟ Failure("wrongerror")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment