Skip to content

Instantly share code, notes, and snippets.

@channingwalton
Forked from YoEight/monadwriterexample.scala
Last active December 14, 2015 04:09
Show Gist options
  • Save channingwalton/5026046 to your computer and use it in GitHub Desktop.
Save channingwalton/5026046 to your computer and use it in GitHub Desktop.
object MonadWriterExample extends App {
import scalaz._
import Scalaz._
implicit val monadWriter = EitherT.listenableMonadWriter[Writer, String, String]
case class Person(firstName: String, age: Int, car: Option[String])
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, car: Option[String]) = for {
n ← notEmpty(firstName) :++>> (x ⇒ "The first name is => " + x + "\n")
a ← majority(age) :++>> (x ⇒ "She is an adult => " + x + "\n")
_ ← if (car.isDefined) monadWriter.tell("Got a car") else monadWriter.tell("No car.")
} yield Person(n, a, car)
}
@channingwalton
Copy link
Author

Is the line that tests whether a car is defined in validateData 'a good way' of doing what its doing? I am simply logging something but proceeding anyway regardless of the value.

@YoEight
Copy link

YoEight commented Feb 25, 2013

For me there's nothing wrong with that. Do you really need to notify "No car" ? If you don't, you could write

car.traverse(_ => monadWriter.tell("Got a car"))

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