Skip to content

Instantly share code, notes, and snippets.

@paradigmatic
Created February 23, 2012 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paradigmatic/1891147 to your computer and use it in GitHub Desktop.
Save paradigmatic/1891147 to your computer and use it in GitHub Desktop.
ValidReader
import scalaz._
import Scalaz._
object MapReader extends App {
type ValidReader[S,X] = (S) => Validation[NonEmptyList[String],X]
type MapReader[X] = ValidReader[Map[String,String],X]
def read[A: Manifest]( key: String )( f: String => A ): MapReader[A] =
map => {
if( ! map.contains(key) ) {
("Missing key: " +key).fail
} else {
try {
f( map(key) ).success
} catch {
case _ => {
val value = map(key)
val klass = implicitly[Manifest[A]].erasure
("Cannot convert '" + value + "' to " + klass).fail
}
}
}
}.liftFailNel
def readInt( k: String ): MapReader[Int] = read[Int](k)( _.toInt )
def readString( k: String ): MapReader[String] = read[String](k)( s => s )
val name = readString( "name" )
val age = readInt( "age" )
val data = Map( "name" -> "Paul", "age" -> "8" )
println( name(data) )
println( age(data) )
case class Boy( name: String, age: Int )
val boy = ( name |@| age ) {
(n,a) => ( n |@| a ) { Boy(_,_) }
}
println( boy( data ) )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment