functional programming - How to shorten this OCaml code? -
i wondering how shorten these code suspect redundant
let ename doc = try (stringmap.find ename doc) not_found -> none;; let get_double ename doc = let element = ename doc in match element | none -> none | (double v) -> v | _ -> raise wrong_bson_type;; let get_string ename doc = let element = ename doc in match element | none -> none | (string v) -> v | _ -> raise wrong_bson_type;; let get_doc ename doc = let element = ename doc in match element | none -> none | (document v) -> v | _ -> raise wrong_bson_type;;
so, basically, have different types of values, , put kinds of values map.
the code above getting according type of values out of map. each type, have get. 1 type of value, have see a). whether there or not; b). whether type indeed, if not, raise exception.
but code above seems redundant can see. diff between each type's type itself.
how can shorten code?
you can this:
let get_generic extract ename doc = let element = ename doc in match element | none -> none | v -> (extract v) let get_double = get_generic (function double v -> v | _ -> raise wrong_bson_type) let get_string = get_generic (function string v -> v | _ -> raise wrong_bson_type) let get_doc = get_generic (function document v -> v | _ -> raise wrong_bson_type)
edit: remove redundant raise wrong_bson_type
(but ugly):
let get_generic extract ename doc = try let element = ename doc in match element | none -> none | v -> (extract v) match_failure _ -> raise wrong_bson_type let get_double = get_generic (fun (double v) -> v) let get_string = get_generic (fun (string v) -> v) let get_doc = get_generic (fun (document v)-> v)