public
Created

ValidReader

  • Download Gist
MapReader.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
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 ) )
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.