开发者

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

开发者 https://www.devze.com 2023-02-25 16:06 出处:网络
let rec map2 (f : \'a * \'b -> \'c) (l1 : \'a list) (l2 : \'b list) : \'c list = match (l1,l2) with
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

W开发者_运维百科hat am I doing wrong here??


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消