1
votes

I have a very interesting first project to learn OCaml, after creating a personnal list type like such:

type 'a my_list = Item of ('a * 'a my_list) | Empty;;

And filling it up like such:

let num_list = Item (1, Item (2, Item(3, Empty)));;

I have to recode many functions of the list module which will be adapted to my new list type as showed above.

I'm starting off with Length which sounds the easiest and a good one to start with.

Here's what I have so far:

let rec length my_list =
match my_list with
| [] -> 0
| head::rest -> 1 + (length rest);;

Which has the right definition:

val length : 'a list -> int = <fun>

But when I pass my newly created list I get the following error:

Error: This expression has type int my_list but an expression was expected of type 'a list

What am I missing out?

I'm enjoying OCaml so far, and would really appreciate your help.

1

1 Answers

2
votes

You are not actually using your own 'a my_list type but the original 'a list.

Your function has to do a pattern matching, not on a 'a list but on a 'a my_list:

let rec my_length my_list = 
  match my_list with
  | Empty -> 0
  | Item (_, rest) -> 1 + (my_length rest);;

The type that you get now is :

val my_length : 'a my_list -> int = <fun>

Now you are using your own 'a my_list type.