Skip to content

Instantly share code, notes, and snippets.

@ezzahraoui
Created May 9, 2016 11:17
Show Gist options
  • Save ezzahraoui/470450ac0a7e4993c1f796b3f07036a6 to your computer and use it in GitHub Desktop.
Save ezzahraoui/470450ac0a7e4993c1f796b3f07036a6 to your computer and use it in GitHub Desktop.
Play Json read/write for spire.math.Interval
import spire.math._
import spire.math.interval._
import spire.implicits._
import play.api.libs.json._
implicit object IntervalFormat extends Format[Interval[Double]] {
def reads(json: JsValue): JsResult[Interval[Double]] = {
def JsValueToBound(jsValue: JsValue): Bound[Double] = {
val boundType = (jsValue \ "type").as[String]
boundType match {
case "closed" =>
val boundValue = (jsValue \ "value").as[Double]
Closed(boundValue)
case "open" =>
val boundValue = (jsValue \ "value").as[Double]
Open(boundValue)
case "unbound" => Unbound[Double]()
case "emptybound" => EmptyBound[Double]()
}
}
val lower: Bound[Double] = JsValueToBound((json \ "lower").as[JsValue])
val upper: Bound[Double] = JsValueToBound((json \ "upper").as[JsValue])
JsSuccess(Interval.fromBounds(lower, upper))
}
def writes(interval: Interval[Double]): JsValue = {
def boundToJsValue(bound: Bound[Double]): JsValue = {
bound match {
case Closed(value) =>
Json.obj("type" -> "closed", "value" -> value)
case Open(value) =>
Json.obj("type" -> "open", "value" -> value)
case Unbound() =>
Json.obj("type" -> "unbound")
case EmptyBound() =>
Json.obj("type" -> "emptybound")
}
}
Json.obj(
"lower" -> boundToJsValue(interval.lowerBound),
"upper" -> boundToJsValue(interval.upperBound))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment