Created
September 17, 2010 16:59
-
-
Save kowey/584546 to your computer and use it in GitHub Desktop.
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
| class RelTriple(subj:String,pred:String,obj:String) | |
| object RelTriple { | |
| def fromJson(j:Any):Option[RelTriple] = { | |
| return j match { | |
| case m:Map[String,Any] => | |
| // FIXME: how do I avoid all those coercions | |
| // or somehow move theme to a better place? | |
| (m get "subject") flatMap ((s:Any) => | |
| (m get "object") flatMap ((o:Any) => | |
| (m get "predicate") flatMap ((p:Any) => | |
| Some(new RelTriple(s.asInstanceOf[String], | |
| p.asInstanceOf[String], | |
| o.asInstanceOf[String]) | |
| )))) | |
| case _ => None | |
| } | |
| } | |
| } | |
| object Foo { | |
| def parseRelations(s:String): Option[List[List[RelTriple]]] = { | |
| val fromInnerList = JsonHelper.fromJsonList(_:Any,RelTriple.fromJson) | |
| val fromOuterList = JsonHelper.fromJsonList(_:Any,fromInnerList) | |
| fromOuterList(JSON.parseFull(s)) | |
| } | |
| } | |
| // FIXME: I'm sure there's a more idiomatic way of saying what I want here | |
| object JsonHelper { | |
| def allDefined[A] (x:List[Option[A]]):Option[List[A]] = { | |
| if (x forall (x => x.isDefined)) { | |
| Some(x map (y => y.get)) | |
| } else { | |
| None | |
| } | |
| } | |
| def fromJsonList[A](j:Any, f:Any => Option[A]):Option[List[A]] = { | |
| return j match { | |
| case x:List[Any] => allDefined(x map f) | |
| case _ => None | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment