在 Ocaml 语言中,目标是组合(追加)两个列表,同时删除重复项。
let rec find_dup a lst =
match lst with
| [] -> false
| hd::tl -> if (hd == a) then true else find_dup a tl;;
let rec app lst2 lst1 =
match lst1 with
| [] -> lst2
| hd::tl -> if (find_dup hd lst2) then (app tl lst2)
else hd::app tl lst2
;;
我的代码是这样的,但是当测试用例是
app [4;5;6;7] [1;2;3;4]
答案应该是[1;2;3;4;5;6;7]
但我不断得到
- : int list = [1; 2; 5; 3; 6; 4; 7]
发生什么事了?
您要为每个递归调用切换列表。
查看函数定义的参数顺序:
let rec app lst2 lst1
然后递归函数调用:
app tl lst2
另外,顺便提一下,
find_dup
已经存在于标准库中。这叫List.mem
。