Skip to content

Instantly share code, notes, and snippets.

@rapha
Created May 8, 2012 02:54
Show Gist options
  • Save rapha/2632205 to your computer and use it in GitHub Desktop.
Save rapha/2632205 to your computer and use it in GitHub Desktop.
Demo argv parsing in Ocaml
module Args = struct
type 'a arg_spec = { name: string; desc: string; of_string: (string -> 'a) }
exception RequiredArgMissing of string (* name *)
exception BadArgValue of string * string (* name, value *)
let find_given_value spec =
(* TODO allow user to specify argv *)
let arg_list = Array.to_list Sys.argv in
let flag = "-" ^ (spec.name) in
let rec find_value_in = function
| [] | [_] -> None
| name :: value :: _ when name = flag -> Some value
| _ :: rest -> find_value_in rest
in
find_value_in arg_list
(* TODO: Add other types. *)
let custom ~name ~desc ~of_string = { name; desc; of_string }
let bool ~name ~desc = custom ~name ~desc ~of_string:bool_of_string
let float ~name ~desc = custom ~name ~desc ~of_string:float_of_string
let int ~name ~desc = custom ~name ~desc ~of_string:int_of_string
let string ~name ~desc = custom ~name ~desc ~of_string:(fun s -> s)
let get spec =
(* Allow user to specify the argv *)
match find_given_value spec with
| Some str -> begin
try Some (spec.of_string str)
with _ -> raise (BadArgValue (spec.name, str))
end
| None -> None
let get_or_default spec default =
match get spec with
| Some value -> value
| None -> default
let require spec =
match get spec with
| Some value -> value
| None -> raise (RequiredArgMissing spec.name)
end
let _ =
let go_faster = Args.bool ~name:"go_faster" ~desc:"Whether to go faster" in
let awesomeness = Args.float ~name:"awesomeness" ~desc:"How awesome to be" in
print_endline begin
match Args.get go_faster with
| Some true -> "quickly"
| Some false -> "slowly"
| None -> "?"
end;
Printf.printf "awesomeness: %f" (Args.require awesomeness)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment