Created
November 28, 2013 10:34
-
-
Save xuwei-k/7689965 to your computer and use it in GitHub Desktop.
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
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 | |
""" |
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
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