Created
August 8, 2012 06:47
-
-
Save YoEight/3292879 to your computer and use it in GitHub Desktop.
Monad Writer Example
This file contains 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
package scalaz | |
import scalaz.std.string._ | |
import scalaz.syntax.listenableMonadWriter._ | |
object MonadWriterExample extends App { | |
implicit val monadWriter = EitherT.listenableMonadWriter[Writer, String, String] | |
case class Person(firstName: String, age: Int) | |
def notEmpty(s: String) = Option(s).filter(x => !x.isEmpty && !x.forall(_.isWhitespace)) match { | |
case Some(r) => monadWriter.right[String](r) | |
case None => monadWriter.left[String]("Empty String") | |
} | |
def majority(age: Int) = | |
if(age >= 18) monadWriter.right[Int](age) | |
else monadWriter.left[Int]("This person is not an adult") | |
def validateData(firstName: String, age: Int) = for { | |
n <- notEmpty(firstName) :++>> (x => "The first name is => " + x + "\n") | |
a <- majority(age) :++>> (x => "She is an adult => " + x + "\n") | |
} yield Person(n, a) | |
def showMe(v: (Person, String)) { | |
println("Log produced during computation -------") | |
println(v._2) | |
println("Computation result --------------------") | |
println(v._1) | |
} | |
println(validateData("", 17).listen.map(showMe).run.run) // showMe will not be called, no log accumulated | |
println() | |
println() | |
println(validateData("Nath", 5).listen.map(showMe).run.run) // showMe will not be called: log value is "Firstname name is => Nath" | |
println() | |
println() | |
validateData("Mimie", 20).listen.map(showMe) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment