Skip to content

Instantly share code, notes, and snippets.

@mjambon
Last active August 16, 2016 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjambon/71ccc6d4e4f2f4529077070f12167ffb to your computer and use it in GitHub Desktop.
Save mjambon/71ccc6d4e4f2f4529077070f12167ffb to your computer and use it in GitHub Desktop.
An abstract type for reading any number into an int with atdgen
(*
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
@mjambon
Copy link
Author

mjambon commented Aug 16, 2016

This isn't pretty or convenient but gets the job done. A solution built into atdgen would be more convenient.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment