Skip to content

Instantly share code, notes, and snippets.

@tmyymmt
Created September 16, 2012 16:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tmyymmt/3733172 to your computer and use it in GitHub Desktop.
Save tmyymmt/3733172 to your computer and use it in GitHub Desktop.
def compute1(maybeFoo: Option[Foo]): Option[Int] =
for {
foo <- maybeFoo
bar <- foo.bar
baz <- bar.baz
} yield baz.compute
// for compute2
import scalaz._
import Scalaz._
sealed trait Validation[E, A] {
def map[B](f: A => B): Validation[E, B]
def flatMap[B](f: A => Validation[E, B]): Validation[E, B]
def liftFail[F](f: E => F): Validation[F, A] // unrelated to monads!
}
case class Success[E, A](a: A) extends Validation[E, A] {
def map[B](f: A => B): Validation[E, B] = new Success(f(a))
def flatMap[B](f: A => Validation[E, B]): Validation[E, B] = f(a)
def liftFail[F](f: E => F): Validation[F, A] = new Success(a)
}
case class Failure[E, A](e: E) extends Validation[E, A] {
def map[B](f: A => B): Validation[E, B] = new Failure(e)
def flatMap[B](f: A => Validation[E, B]): Validation[E, B] = new Failure(e)
def liftFail[F](f: E => F): Validation[F, A] = new Failure(f(e))
}
def compute2(foo: Foo): Validation[ComputeException, Int] =
for {
bar <- foo.bar.liftFail { new ComputeException(_) }
baz <- bar.baz.liftFail { new ComputeException(_) }
result <- baz.compute
} yield result
@tmyymmt
Copy link
Author

tmyymmt commented Sep 16, 2012

Scala Monads: Declutter Your Code With Monadic Design - Marakana
http://marakana.com/s/scala_monads_declutter_your_code_with_monadic_design,1034/index.html

@kell18
Copy link

kell18 commented Mar 4, 2016

Hi!
There is no liftFail method in Scalaz Validation today.. :(
How i can use this feature?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment