Reputation: 2044
I want to write a function that will combine all the elements in a list in OCaml. Simple enough, so far I have a working function:
let rec comAll (f : 'a -> 'a -> 'a) (r : 'a) (l : 'a list) : 'a =
match l with [] -> r
| hd::tl -> let comAll2 = comAll f r tl in f hd comAll2
;;
The First argument is a function, the second is a default value to return when/if the input list is empty, and the third argument is the list itself.
This function works as intended, except when I try to call it using another function, for example:
let inList (l : 'a list) (e : 'a) : bool = comAll (fun x y -> if x == e then true else y) false l ;;
which will pass as a function, returning inList : bool list -> bool -> bool = <fun>
however, I want to instead have it return inList : 'a list -> 'a -> bool = <fun>
I have tried instead defining comAll as: let rec comAll f r l =...
and that works, but I want to declare the function with explicit types.
Any help or guidance on what I am doing incorrect here?
Upvotes: 0
Views: 59
Reputation: 66823
You are declaring your parameter f
to be of type 'a -> 'a -> 'a
but you want to pass a function of type 'a -> bool -> bool
. In other words, you want to have two different types. You should declare f
to be of type 'a -> 'b -> 'b
. The rest will follow.
# let rec comAll (f : 'a -> 'b -> 'b) (r : 'b) (l : 'a list) : 'b =
match l with [] -> r
| hd::tl -> let comAll2 = comAll f r tl in f hd comAll2 ;;
val comAll : ('a -> 'b -> 'b) -> 'b -> 'a list -> 'b = <fun>
# let inList (l : 'a list) (e : 'a) : bool =
comAll (fun x y -> if x == e then true else y) false l;;
val inList : 'a list -> 'a -> bool = <fun>
Upvotes: 1