Sorry, an error occurred while loading the content.

## Re: "List.index" or "List.unique" functions?

Expand Messages
• ... Hopefully, in another year, the libraries will be good too. ... Your algorithm is O(n^2). More sensible approaches include: * Sort the list and remove the
Message 1 of 1 , Apr 30, 2004
In article <20040430175429.GB11118@...>, Rahul Siddharthan wrote:
> I just discovered OCaml a week or so ago, and it really seems to be
> the "holy grail" -- more concise and elegant that python, almost as
> fast as C. I wish I'd known of it a year ago. Now I just need to
> get used to the functional way of thinking...

Hopefully, in another year, the libraries will be good too.

> 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])
>
> In python, I can define a function to do this quite concisely, eg:
>
> unique = lambda l: [l[n] for n in range(len(l)) if l.index(l[n])==n]

Your algorithm is O(n^2).
More sensible approaches include:
* Sort the list and remove the duplicates
* Shove the elements of the list into a set, then get the keys of
the set

Note that the ocaml "list" is a linked list. I don't really know
python, but I imagine that, as in perl, a python "list" is actually an
array. Ocaml has separate list and array types, reflecting ocaml's
closer-to-the-hardware nature.

Alan
Your message has been successfully submitted and would be delivered to recipients shortly.