tags:

views:

85

answers:

2

Hi All,

Here is the code on sorting any given list:

let rec sort lst =
   match lst with
     [] -> []
   | head :: tail -> insert head (sort tail)
 and insert elt lst =
   match lst with
     [] -> [elt]
   | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;

[Source: Code

However, I am getting an Unbound error:

Unbound value tail
# let rec sort lst =
   match lst with
     [] -> []
   | head :: tail -> insert head (sort tail)
 and insert elt lst =
   match lst with
     [] -> [elt]
   | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;
Characters 28-29:
     | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;
     ^
Error: Syntax error

Can anyone please help me understand the issue here?? I did not find head or tail to be predefined anywhere nor in the code

+1  A: 

Your code seems correct, and compiles for me:

    Objective Caml version 3.11.1

# let rec sort lst = ...

val sort : 'a list -> 'a list = <fun>
val insert : 'a -> 'a list -> 'a list = <fun>

# sort [ 1 ; 3 ; 9 ; 2 ; 5 ; 4; 4; 8 ; 4 ] ;;
- : int list = [1; 2; 3; 4; 4; 4; 5; 8; 9]
Pascal Cuoq
But I did not understand what the pattern "head :: tail" means. Can you please explain?
darkie15
The type list is a built-in type defined as having two constructors. One is the empty list `[]`. The other is the cons cell `::`. The pattern matchings you have written are no different from the pattern matchings you could write for types you would have defined yourself, except that they use the built-in 0-ary constructor [] and binary ::.
Pascal Cuoq
In the pattern `head :: tail`, the variable `head` represents the first element of the list, and `tail` the rest of the list.
Pascal Cuoq
Compiles and runs with 3.10 as well.
Norman Ramsey
Hi,I am still getting the error : http://www.easy-share.com/1910132443/Error.bmpCan you please help me find out the reason?Regards,darkie
darkie15
A: 

Adding to what Pascal said, the list type is defined as:

type 'a list = [] | :: of 'a * 'a list

and that's what you are matching your list lst against.

M.S.
Hi,I am still getting the error : http://www.easy-share.com/1910132443/Error.bmpCan you please help me find out the reason?Regards,darkie
darkie15