Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] "List.index" or "List.unique" functions?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Benjamin Geer <ben@s...>
Subject: Re: [Caml-list] "List.index" or "List.unique" functions?
Rahul Siddharthan wrote:
> I have a question: suppose I have a list l1, and I want to create a new
> list l2 with only one copy of any repeated members of the first list
> (eg, l1=[1;2;3;4;3;4;5;6;5] -> l2=[1;2;3;4;5;6])

Here's one way:

let unique ls =
   let uniq_aux new_ls old_elem =
     match new_ls with
       | [] -> [ old_elem ]
       | hd :: tl when hd = old_elem -> new_ls
       | _ -> old_elem :: new_ls
   in
   let sorted = List.sort compare ls in
     List.rev (List.fold_left uniq_aux [] sorted) ;;

Ben

-------------------
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