This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] List.sort
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2002-06-19 (15:20) From: Henri Dubois-Ferriere Subject: Re: [Caml-list] List.sort
```A simple example:

# let l = [4; 3; 2; 1];;
val l : int list = [4; 3; 2; 1]
# List.sort compare l;;
- : int list = [1; 2; 3; 4]

# List.sort;;
- : ('a -> 'a -> int) -> 'a list -> 'a list = <fun>

you can interpret the signature as follows:

1st argument, of type ('a -> 'a -> int): 'compare' function
a function that takes two
arguments of identical type, and returns an int.

2nd argument, of type 'a list : list of the *same* type as the arguments
of the function passed as the compare function.

> According to the manual the Persvasives.compare function is suitable
> to use with List.sort.  I can't figure out how to use it:
> ----------------------------
> # k;;
> - : int list = [3; 2; 1]
> # List.sort (compare 1 2) k;;
> This expression has type int but is here used with type 'a -> 'a ->
> int

indeed, (compare 1 2) evaluates to an int :

# compare 1 2;;
- : int = -1

> # List.sort (+) k;;
> - : int list = [1; 2; 3]
> # a;;

this is accepted because (+) takes the right arguments (two ints). Your
list is sorted, but that is just by coincidence ;)

> - : char list = ['d'; 'b'; 'g']
> # List.sort (+) a;;
> This expression has type char list but is here used with type int list

As noted above, the second argument passed to List.sort takes a list whose
elements must be of same type as the compare function. Here your compare
function (+) takes int's, and you are giving a list of char's ...

> # List.sort (compare 'a' 'b') a;;
> This expression has type int but is here used with type 'a -> 'a ->
> int
> # compare 'a' 'b';;
> - : int = -1
> #
> ---------------------

same argument as for the first case: (compare 'a' 'b') is a char, not a
function.

Henri

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

```