From: Miguel Pignatelli <miguel.pignatelli@uv.es>
To: caml-list@inria.fr
Subject: Re: [Caml-list] New to Ocaml
Date: Tue, 02 Feb 2010 08:22:22 +0100 [thread overview]
Message-ID: <4B67D2AE.6000008@uv.es> (raw)
In-Reply-To: <20100202152707.8f4a1e24.mle+ocaml@mega-nerd.com>
> 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
next prev parent reply other threads:[~2010-02-02 7:22 UTC|newest]
Thread overview: 5+ messages / expand[flat|nested] mbox.gz Atom feed top
2010-02-02 4:18 chaithanya kr
2010-02-02 4:27 ` [Caml-list] " Erik de Castro Lopo
2010-02-02 7:22 ` Miguel Pignatelli [this message]
2010-02-02 8:58 ` Richard Jones
2010-02-02 13:04 ` chaithanya kr
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=4B67D2AE.6000008@uv.es \
--to=miguel.pignatelli@uv.es \
--cc=caml-list@inria.fr \
--cc=pignatelli_mig@gva.es \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox