Last active
August 16, 2016 00:52
-
-
Save mjambon/71ccc6d4e4f2f4529077070f12167ffb to your computer and use it in GitHub Desktop.
An abstract type for reading any number into an int with atdgen
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
(* | |
An atdgen type for reading any number into an int. | |
`1.0` is the default output for the atd type float, which | |
we want to support but is not supported by the regular parser | |
for atd type int. | |
`1.0` will be read as the OCaml int `1` and written back as `1`. | |
The definition that goes into the .atd file is: | |
type rounded <ocaml module="Rounded" t="t"> = abstract | |
*) | |
type t = int | |
(* | |
Round a float to the nearest int | |
*) | |
let round x = | |
if x > 0. then | |
truncate (x +. 0.5) | |
else | |
truncate (x -. 0.5) | |
let test_round () = | |
assert (round 123.45 = 123); | |
assert (round 0.6 = 1); | |
assert (round 0.4 = 0); | |
assert (round (-0.4) = 0); | |
assert (round (-0.6) = -1); | |
true | |
let read_t ls lb = | |
let x = Yojson.Basic.read_number ls lb in | |
round x | |
let write_t ob x = | |
Yojson.Basic.write_int ob x | |
let validate_t path x = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This isn't pretty or convenient but gets the job done. A solution built into atdgen would be more convenient.