Skip to content

Instantly share code, notes, and snippets.

@mjambon
Last active February 26, 2016 02:05
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/c9e0a3e06b084ff065ce to your computer and use it in GitHub Desktop.
Save mjambon/c9e0a3e06b084ff065ce to your computer and use it in GitHub Desktop.
type json = [
| `Bool of bool
| `Int of int
| `Object of (string * json) list
]
type _ path =
| Bool : bool path
| Int : int path
| Field : string * 'a path -> 'a path
let rec find : type a . json -> a path -> a option = fun json path ->
match json, path with
| `Bool b, Bool -> Some b
| `Int i, Int -> Some i
| `Object l, Field (k, p) ->
(try
let v = List.assoc k l in
find v p
with Not_found ->
None
)
| _ ->
None
let json = `Object [ "x", `Bool true;
"y", `Int 123 ]
let x = find json (Field ("x", Bool)) (* Some true *)
let y = find json (Field ("y", Int)) (* Some 123 *)
let nothing = find json (Field ("y", Bool)) (* None *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment