Ocaml将列表附加到另一个列表而不重复

时间:2012-04-22 20:12:16

标签: list append ocaml

我的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)
;;

但是当我使用它时看起来效果不好,事实证明仍然存在重复的元素。

请看一下上述功能,并就如何纠正它们给我一些建议......

谢谢=)

1 个答案:

答案 0 :(得分:4)

如果您使用Set,则只需要将两套联合起来。

如果l2中的help_append_list没有重复,那么您的功能正常。

假设xy可能有自己的重复,订单无关紧要,您可以使用:

let append_list x y = help_append_list x (help_append_list y [])

我对你的功能有一些评论。首先,findList module中的exists函数相同。您可能希望将其编写用于学习目的,因此if (h = e) then true else ...应替换为||

let rec find e = function
    | [] -> false
    | h::t -> h = e || find e t

其次,[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)
相关问题