From mboxrd@z Thu Jan 1 00:00:00 1970 Received: (from majordomo@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id IAA10056; Thu, 28 Jun 2001 08:47:25 +0200 (MET DST) X-Authentication-Warning: pauillac.inria.fr: majordomo set sender to owner-caml-list@pauillac.inria.fr using -f Received: from nez-perce.inria.fr (nez-perce.inria.fr [192.93.2.78]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id IAA10010 for ; Thu, 28 Jun 2001 08:47:24 +0200 (MET DST) Received: from ext.lri.fr (ext.lri.fr [129.175.15.4]) by nez-perce.inria.fr (8.11.1/8.10.0) with ESMTP id f5S6lND02270 for ; Thu, 28 Jun 2001 08:47:23 +0200 (MET DST) Received: from pc87 (pc87 [129.175.8.106]) by ext.lri.fr (8.11.1/jtpda-5.3.2) with SMTP id f5S6l9526032 ; Thu, 28 Jun 2001 08:47:10 +0200 (MET DST) Date: Thu, 28 Jun 2001 08:47:09 +0200 From: Judicaël Courant To: Chris Hecker Cc: caml-list@inria.fr Subject: Re: [Caml-list] there has to be a better way to write this code Message-Id: <20010628084709.201e7770.Judicael.Courant@lri.fr> In-Reply-To: <200106280300.UAA18698@smtp4-cm.mail.eni.net> References: <200106280300.UAA18698@smtp4-cm.mail.eni.net> X-Mailer: Sylpheed version 0.4.64 (GTK+ 1.2.7; i386-debian-linux-gnu) Organization: LRI Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit Sender: owner-caml-list@pauillac.inria.fr Precedence: bulk Hi, On Wed, 27 Jun 2001 20:00:27 -0700 Chris Hecker 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