Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Multi-keyed lookup table?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: ijtrotts@u...
Subject: Re: [Caml-list] Array.filter (was Multi-keyed lookup table?)
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 = <fun>
# let odd = fun x -> x land 1 = 1;;
val odd : int -> bool = <fun>
# 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