Created
May 9, 2016 11:17
-
-
Save ezzahraoui/470450ac0a7e4993c1f796b3f07036a6 to your computer and use it in GitHub Desktop.
Play Json read/write for spire.math.Interval
This file contains 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 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