ice
ice

Reputation: 21

Ocaml error about 'a list list

# let rec nth l n =
    match l with
     [] -> []
    |h::t -> if n = 0 then h
        else nth t (n-1);;
val nth : 'a list list -> int -> 'a list = <fun>
# let rec drop n l =
   if n = 0 then l else
     match l with
       [] -> []
      |h::t -> drop (n-1) t;;
val drop : int -> 'a list -> 'a list = <fun>
# let rec zipper a b =
    match a with
     [] -> b
    |h::t -> h :: nth b 0 :: zipper t (drop 1 b);;
val zipper : 'a list list -> 'a list list -> 'a list list = <fun>
# zipper [1;3;5] [2;4;6];;
Characters 8-9:
  zipper [1;3;5] [2;4;6];;
          ^
Error: This expression has type int but an expression was expected of type
         'a list

I was trying to combine two lists together. Each step seemed ok but when I typed the last sentence zipper [1;3;5] [2;4;6] the error emerged.

I learned type 'a in 'a list can be any type in Ocaml. Then, the expression type int is ok I thought.. I don't know whats wrong

Upvotes: 2

Views: 861

Answers (1)

Ptival
Ptival

Reputation: 9437

Your problem is in nth, as you return an empty list in the base case, rather than an element of the type inside the list! Therefore Ocaml infers that your list contains lists.

You can fix it a few ways:

  • raise an exception or use failwith in the case where the list is empty

  • pass an additional argument which is a default value to return

  • return an option type, so that you can return Some(result) when things work out, and None when there is a problem

Upvotes: 1

Related Questions