Skip to content

Instantly share code, notes, and snippets.

@kowey
Created September 17, 2010 16:59
Show Gist options
  • Select an option

  • Save kowey/584546 to your computer and use it in GitHub Desktop.

Select an option

Save kowey/584546 to your computer and use it in GitHub Desktop.
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