0
votes

I'm brand new to OCaml, and was trying to make a function to see if a list x was a subset of y, and I'm not sure where I'm going wrong. I've read a bunch of similar problems, and they all list type conflict as the cause, but I'm not sure where I have any sort of conflict.

# let header x = List.hd x;;
val header : 'a list -> 'a = <fun>
# let matcher x y = List.mem x y;;
val matcher : 'a -> 'a list -> bool = <fun>
# let tailer x = List.tl x;;
val header : 'a list -> 'a = <fun>
# let rec sub x y =
  if ((List.length x) == 0) then true
  else if (matcher (header x) y) then sub((tailer x) y)
  else false;;
Error: This expression has type 'a list
       This is not a function; it cannot be applied.

In rec sub x y, I can either return 'true' for an empty list x, redo sub on the List.tl of x, aka the list without the head (from what I understand), or just return a false if I wasn't able to find the current head of x in y. The recursion would have to eventually lead to either a true or false, so I don't see where a type conflict could arise.

1
For best results, I'd suggest you access list elements only via pattern-matching. You may not even need to use functions from the List module. For example, you can check if a list is empty without computing its length using match ... with [] -> ... | head :: tail -> .... - Martin Jambon

1 Answers

0
votes

In

sub((tailer x) y)

The outer parentheses means you're applying y to the result of tailer x. The error message tells you that this result is an 'a list, not a function. It also means you're only passing a single argument to 'sub', the result of applying y to tailer x.

I'm not entirely sure why you believe these parentheses are necessary, but it seems likely you're confusing it with C-style function application, and simply removing them solves the error.

It might also be worth noting that, because of currying, (tailer x) y and tailer x y is equivalent. So you either mean sub (tailer x y) or sub (tailer x) y. In either case there's too many parentheses.