Created
February 23, 2012 06:45
-
-
Save paradigmatic/1891147 to your computer and use it in GitHub Desktop.
ValidReader
This file contains hidden or 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
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