Last active
December 10, 2015 02:19
-
-
Save YoEight/4366863 to your computer and use it in GitHub Desktop.
A MonadWriter example using Scala 2.9.2 and Scalaz 7.0.0-M7
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
package gist | |
import 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)/*: EitherT[({type f[+x] = Writer[String, x]})#f, String, 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)/*: EitherT[({type f[+x] = Writer[String, x]})#f, String, Int]*/ = | |
if(age >= 18) monadWriter.right[Int](age) | |
else monadWriter.left[Int]("This person is not an adult") | |
def validateData(firstName: String, age: Int): EitherT[({type f[+x] = Writer[String, x]})#f, String, Person] = 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) | |
} |
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
[info] Running gist.MonadWriterExample | |
(,-\/(Empty String)) | |
(The first name is => Nath | |
,-\/(This person is not an adult)) | |
Log produced during computation ------- | |
The first name is => Mimie | |
She is an adult => 20 | |
Computation result -------------------- | |
Person(Mimie,20) | |
[success] Total time: 13 s, completed 24 déc. 2012 01:11:53 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment