0
votes

Here is my code:

let rec intersection l1 l2 res = 
match l1 with
    | [] -> res
    | h1 :: t1 ->
    (
        match l2 with
        | [] -> []
        | h2 :: t2 ->
        if member h1 l2 = true then 
            intersection t1 l2 h1::res 
        else 
            intersection t1 l2 res
    )

the issue is with h1::res part it throws the following error:

Error: This expression has type 'a list but an expression was expected of type 'a The type variable 'a occurs inside 'a list

But if I replace h1::res with [h1]@res then the code works, I am not getting the exact reason for this issue, please help.

Note: member is a custom function that returns true if an element belongs to the list l2 else false.

1
The problem is operator precedence. That line is parsed as (intersection t1 l2 h1)::res. You mean for it to be intersection t1 l2 (h1::res).glennsl

1 Answers

0
votes

Your issue is the precedence in intersection t1 l2 h1::res. OCaml is trying to evaluate intersection t1 l2 h1 and then cons that to res, which is of type `'a list. You need to specify operator precedence manually. You can either do

intersection t1 l2 (h1::res)

or, you can use the application operator from the Pervasives module. As noted in the documentation, g @@ f @@ x is the same as g (f (x))

intersection t1 l2 @@ h1::res