为什么会发生这种情况(Ocaml)
在Ocaml语言中,目标是在删除重复项的同时合并(附加)两个列表为什么会发生这种情况(Ocaml),ocaml,Ocaml,在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
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
谢谢,所以我不应该让这个应用程序成为递归函数?但是它在里面吗?不,它应该是递归的。但是调用时不应该交换参数的顺序。因此,解决办法是将它们调回。请不要以使现有答案无效的方式修改问题。我已还原了更改,因此您无需执行任何操作,但请不要再执行此操作。