Rowhawn
Rowhawn

Reputation: 1479

Ocaml type error confusion: why is this making an error?

    let rec add_tail l e = match l with
      | [] -> [e]
      | (h::t) -> h::(add_tail t e)

    let rec fill_help l x n = match n = 0 with
      true -> l
      | false -> add_tail(l, x); fill_help(l, x, n-1)

    let fill x n = 
      let l = [] in
      fill_help(l, x, n)

and I'm getting the error in the interpreter

    # #use "prac.ml";;
    val prod : int list -> int = <fun>
    val add_tail : 'a list -> 'a -> 'a list = <fun>
    File "prac.ml", line 13, characters 21-27:
    Error: This expression has type 'a * 'b
           but an expression was expected of type 'c list

line 13 would be

    | false -> add_tail(l, x); fill_help(l, x, n-1)

Upvotes: 2

Views: 904

Answers (1)

sepp2k
sepp2k

Reputation: 370445

First of all you call fill_help with a tuple as an argument ((l, x, n-1)) even though it's not defined to take one. You should call fill_help as fill_help l x (n-1) instead. Same for add_tail.

Secondly you call a side-effect-free function (add_tail) and throw away its return value. This is almost always an error. It looks like you expect l to be different after the call to add_tail. It won't be. You probably want fill_help (add_tail l x) x (n-1).

Upvotes: 4

Related Questions