为什么 If 语句在以下 OCaml 程序中显示错误?

Why is If statement is showing error in following OCaml program?

我是OCaml的新手,请帮助我了解以下错误的原因。

let rec union l1 l2= match l2 with
 []->l1
 |x::xs->if not(List.mem x l1) then l1@[x];union l1 xs ;;

Characters 80-86:
   |x::xs->if not(List.mem x l1) then l1@[x];union l1 xs;;
                                      ^^^^^^   

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

没有 elseif 需要类型 unit,但你的类型为 'a list。这样想:如果你的条件为假,你希望你的函数是什么 return?

PS: l1 @ [x] 是一个没有任何副作用的表达式。将其作为自己的声明而不对其结果做任何事情将一事无成。您可能想使用 l1@[x] 作为 union 的第一个参数,而不仅仅是 l1.

您要实现的算法是:

l2 为空时,return l1,否则当 l2 = x::xs 时:

  • l1 末尾添加 x(如果还没有)
  • 使用 l2 = xs 和新的 l1 递归调用过程。

这不是您的实现所达到的效果。

您的实施执行以下操作: 创建列表 l1@[x],什么也不做。然后进行递归调用。

要使用值 l1@[x],您需要将其绑定到某个名称,例如:

let rec union l1 l2= 
  match l2 with 
  []->l1 
 | x::xs->
   if not(List.mem x l1) 
   then let newl1 = l1@[x] in union newl1 xs
   else union l1 xs

在这里,我还完成了必要的 else 分支,其中包含一些有意义的语句。

你甚至不需要找名字,你可以直接写等价的:

let rec union l1 l2= 
  match l2 with 
  []->l1 
 | x::xs->
   union (if not(List.mem x l1) then l1@[x] else l1) xs