Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.