3
votes

I have the following function table which takes a list of tuples (x's are strings and y's are a list of strings) and I want to return a tuple of x1 and the length of the list y1. I tried it with this simple function:

let rec table lst = function
    | [] -> []
    | [(x1, y1, x2, y2)] -> [(x1, (List.length y1))]
    | (x1_h, y1_h, x2_h, y2_h) :: tail -> (x1_h, (List.length y1_h))::(table tail)

But the following error occured:

Error: This expression has type ('a * 'b list * 'c * 'd) list -> ('a * int) list but an expression was expected of type ('a * int) list

I'm not really sure what I did wrong there.

1

1 Answers

6
votes

function takes an argument implicitly and pattern matches on that. In other words:

let f = function | ...

is equivalent to

let f lst = match lst with | ...

So when you write

let rec table lst = function | ...

That translates to

let rec table lst lst2 = match lst2 with | ...

The error points to the recursive call, table tail, because it is partially applied and returns a function ('a * 'b list * 'c * 'd) list -> ('a * int). table tail tail would return ('a * int list) as expected and is completely valid. But since lst is unused in your function, you can just remove it instead.