Browse thread
[Caml-list] there has to be a better way to write this code
-
Chris Hecker
- Judicaël Courant
- Frederick Smith
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Judicaël Courant <Judicael.Courant@l...> |
| Subject: | Re: [Caml-list] there has to be a better way to write this code |
Hi, On Wed, 27 Jun 2001 20:00:27 -0700 Chris Hecker <checker@d6.com> wrote: > > My problem is that the attached code is really pretty verbose and > redundant. Each of the get_* functions has a lot of duplicate code in > it, and I think there must be a better way. I'd like to write > something like this (not really caml syntax, but you get the idea): > > let get_float h s = get_meta h s (Float el -> el) > let get_float h s = get_meta h s (fun (Float el) -> el) is legal syntax, but IMHO let get_float h s = get_meta h s (fun x -> match x with Float el -> el | _ -> Not_found) would be a bit cleaner Now, what about this for get_meta: let get_meta h s f = let g x = try ignore (f x); true with _ -> false in let s = List.find g (Hashtbl.find_all h s) in f s ;; Or, if you do not want to apply f twice to its argument, you can rewrite find to better suit your needs. The original code is let rec find p = function | [] -> raise Not_found | x :: l -> if p x then x else find p l I suggest: let rec find_and_apply p = function | [] -> raise Not_found | x :: l -> try p x with _ -> find_and_apply p l Then, you can write let get_meta h s f = find_and_apply f (Hashtbl.find_all h s) Hope this helps... Judicaël. -- Judicael.Courant@lri.fr, http://www.lri.fr/~jcourant/ (+33) (0)1 69 15 64 85 ------------------- 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