let sorted_list = List.sort unsorted_list in
You should also provide to List.sort a function to compare the elements
of the list, the function should have type:
'a - 'a - int
For basic types, like ints or chars the Pervasives.compare function
would serve:
# let l = ['g';'b';'f';'c';'a'];;
val l : char list = ['g'; 'b'; 'f'; 'c'; 'a']
# let sortedl = List.sort compare l;;
val sortedl : char list = ['a'; 'b'; 'c'; 'f'; 'g']
For user-defined types (or if you want to write your own comparison
criteria) you should provide the comparison function. For example;
# let sortedl = List.sort (fun x y - if x y then 1 else 0) [5;3;7;1];;
val sortedl : int list = [1; 3; 5; 7]
Hope this helps,
M;
Erik de Castro Lopo wrote:
chaithanya kr wrote:
Hi all. I am new to Ocaml. Just started learning recently.
I was studying lists in ocaml. In that, suppose there is a list by name
singly_list, then by saying List.length singly_list;; I will get the
length of the linked list.
Similarly can anyone tell me as to how to sort a linked list using the
'sort' function? Please give me an example of using List.sort.
In Ocaml, lists are immutable (cannot be changed) and hence, sorting
a list results in a new list:
let sorted_list = List.sort unsorted_list in
Erik
___
Caml-list mailing list. Subscription management:
http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
Archives: http://caml.inria.fr
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs