Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] there has to be a better way to write this code
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Chris Hecker <checker@d...>
Subject: Re: [Caml-list] there has to be a better way to write this code

>Below is my solution.  Its not that different from Judicael Courant's but uses somewhat fewer exceptions.

Ah, for some reason it didn't cross my mind to define my own find function!  I ended up with a hybrid of your two solutions.  I can't decide if the non-exhaustive pattern warning is worse than having to type the 'a option (or your constructive_bool) cases every time:

type data_type =
    String of string
  | Float of float
  | Bool of bool
  | Vector of float * float

let hash_get_meta f h s =
  let rec find f l =
    match l with
      [] -> raise Not_found
    | hd::tl -> 
        try f hd
        with Match_failure _ -> find f tl
  in
  find f (Hashtbl.find_all h s)  
              
let hash_get_string = hash_get_meta (function String el -> el)
let hash_get_bool = hash_get_meta (function Bool el -> el)
let hash_get_float = hash_get_meta (function Float el -> el)
let hash_get_vector = hash_get_meta (function Vector (x,y) -> x,y)

That's pretty close to what I wanted (except for the pattern warnings, dare I ask for a pragma to turn it off locally rather than globally via command line?).  To get rid of them I'd do what you said, but with 'a option instead of defining a new type:

let hash_get_string = hash_get_meta (function String el -> Some el | _ -> None)
let hash_get_float = hash_get_meta (function Float el -> Some el | _ -> None)
let hash_get_bool = hash_get_meta (function Bool el -> Some el | _ -> None)
let hash_get_vector = hash_get_meta (function Vector (x,y) -> Some (x,y) | _ -> None)

Definitely wordier and more redundant, but maybe worth it.

Thanks to all who answered!

Chris


-------------------
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr