Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: Function input ('a * 'b -> 'c)

Tags:

function

ocaml

let rec 

map2 (f : 'a * 'b -> 'c) (l1 : 'a list) (l2 : 'b list) : 'c list =
  match (l1,l2) with
    | ([], []) -> []
    | (x::l1),(y::l2) -> f (x, y)::(map2 f (l1, l2))

It is returning:

Error: This expression has type 'a list * 'a list
   but an expression was expected of type 'a list

What am I doing wrong here??

like image 634
jlaguatan Avatar asked Feb 12 '26 06:02

jlaguatan


1 Answers

The error is map2 f (l1, l2) (as the error location would have told you). You're passing (l1, l2) as a tuple while they should be separate curried parameters : map2 f l1 l2.

Also, your function does not handle the cases of different length (patterns with one list empty but not the other). In this case, the function will raise a match failure, you may want to raise a more specialized error such as invalid_arg "map2" or something.

like image 98
gasche Avatar answered Feb 14 '26 22:02

gasche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!