Skip to content

Instantly share code, notes, and snippets.

@xuwei-k

xuwei-k/build.sbt

Created Nov 28, 2013
Embed
What would you like to do?
libraryDependencies ++= Seq(
"org.scalaz" %% "scalaz-core" % "7.1.0-M4"
)
scalaVersion := "2.10.3"
initialCommands in console := """
import scalaz._
import Scalaz._
import scalaz.std.scalaFuture._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
"""
object Main {
import scalaz._, Scalaz._
case class Person(name: String, age: Int)
type Error = String
val parseName: String => ValidationNel[Error, String] = {
case name if name.nonEmpty && name.forall(('a' to 'z').toSet) =>
Success(name)
case other =>
"invalid name".failNel
}
val parseAge: String => ValidationNel[Error, Int] = { s =>
util.Try(s.toInt).map{
case n if n >= 0 => n.successNel[Error]
case _ => "age must be positive".failNel[Int]
}.getOrElse((s + " is not number").failNel)
}
def parsePerson(name: String, age: String): ValidationNel[Error, Person] =
(parseName(name) |@| parseAge(age))(Person.apply)
implicit val personEqual = Equal.equalA[Person]
implicit val personShow = Show.showA[Person]
def main(args: Array[String]){
parsePerson("foo", "10") assert_=== Success(Person("foo", 10))
parsePerson("foo bar", "10") assert_=== "invalid name".failNel[Person]
parsePerson("foo bar", "aaa") assert_=== NonEmptyList("invalid name", "aaa is not number").fail[Person]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment