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 EAA24812; Mon, 11 Aug 2003 04:36:43 +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 EAA21231 for ; Mon, 11 Aug 2003 04:36:42 +0200 (MET DST) Received: from manzanita (63-217-154-71.greystoneapts.com [63.217.154.71]) by nez-perce.inria.fr (8.11.1/8.11.1) with ESMTP id h7B2aeT20070 for ; Mon, 11 Aug 2003 04:36:41 +0200 (MET DST) Received: from ijtrotts by manzanita with local (Exim 3.36 #1 (Debian)) id 19lg2V-0000nb-00 for ; Sat, 09 Aug 2003 19:34:35 -0700 Date: Sat, 9 Aug 2003 19:34:35 -0700 From: ijtrotts@ucdavis.edu To: caml-list@inria.fr Subject: Re: [Caml-list] Array.filter (was Multi-keyed lookup table?) Message-ID: <20030810023435.GA3019@localhost> References: <005d01c35e51$7c927200$6628f9c1@zofo> <20030809165720.GE21525@swordfish> <20030809184851.GA946@localhost> <20030810195307.GA19113@roke.freak> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <20030810195307.GA19113@roke.freak> User-Agent: Mutt/1.5.4i X-Loop: caml-list@inria.fr X-Spam: no; 0.00; ijtrotts:01 caml-list:01 michal:01 moskal:01 struct:01 yikes:99 incr:01 val:01 issac:01 trotts:01 davis:99 bool:01 center:98 0700,:01 int:01 Sender: owner-caml-list@pauillac.inria.fr Precedence: bulk On Sun, Aug 10, 2003 at 09:53:07PM +0200, Michal Moskal wrote: > On Sat, Aug 09, 2003 at 11:48:51AM -0700, ijtrotts@ucdavis.edu wrote: > > # module Array = struct > > include Array > > let filter f a = Array.init (Array.length a) (fun i -> f a.(i)) > > end;; > > # Array.filter (fun x -> x * x) [| 1;2;3 |];; > > - : int array = [|1; 4; 9|] > > This is map, not filter. Writing filter is more difficult, since you > need to first make list of results and then put them into array (or use > Obj.magic tricks). Yikes, my bad. Here you go: # let filter f a = let n = ref 0 in for i = 0 to Array.length a - 1 do if f a.(i) then incr n done; let k = ref 0 in Array.init !n (fun i -> while not (f a.(!k)) do incr k done; incr k; a.(!k-1));; val filter : ('a -> bool) -> 'a array -> 'a array = # let odd = fun x -> x land 1 = 1;; val odd : int -> bool = # filter odd [| 1;2;3;4;5;6;7;8;9 |];; - : int array = [|1; 3; 5; 7; 9|] Luckily, you don't have to make a list or use Obj.magic. Issac -- Issac Trotts Programmer Center for Neuroscience University of California, Davis ------------------- To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/ Beginner's list: http://groups.yahoo.com/group/ocaml_beginners