我的 Ocaml 项目中有一个帮助功能,可以帮助将一个列表附加到另一个列表中,而不会重复元素。例如,附加list x: [d, e, f, g]到list y [a, b, c, d],结果应该是 [a, b, c, d, e, f, g]
我写的函数是这样的:
(* helper function checks if list contains element *)
let rec find e l =
match l with
[] -> false
|(h::t) -> if (h = e) then true else find e t
;;
(* helper function append l1 to l2 without duplicate *)
let rec help_append_list l1 l2 =
match l1 with
[] -> l2
|(h::t) -> if (find h l2 = false) then (help_append_list t ([h]@l2)) else (help_append_list t l2)
;;
Run Code Online (Sandbox Code Playgroud)
但是当我使用它时,这看起来不太好,结果仍然出现重复的元素。
请看一下上面的函数,并就如何更正它们给我一些建议......
谢谢你=)
如果使用Set,则只需要两个集合的并集即可。
如果l2inhelp_append_list没有重复,则您的功能可以正常工作。
假设,x并且y可以有自己的重复,并且顺序无关紧要,您可以使用:
let append_list x y = help_append_list x (help_append_list y [])
Run Code Online (Sandbox Code Playgroud)
我对你的功能有一些意见。首先,find与List 模块中的exists函数相同。您可能想出于学习目的而编写它,因此应替换为:if (h = e) then true else ...||
let rec find e = function
| [] -> false
| h::t -> h = e || find e t
Run Code Online (Sandbox Code Playgroud)
其次,[h]@l2是一种低效的写法h::l2:
let rec help_append_list l1 l2 =
match l1 with
| [] -> l2
| h::t -> if find h l2 then help_append_list t l2
else help_append_list t (h::l2)
Run Code Online (Sandbox Code Playgroud)