【问题标题】:Ocaml append list to another list without duplicatedOcaml 将列表追加到另一个列表而不重复
【发布时间】:2012-04-23 04:47:13
【问题描述】:

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

但是我用的时候好像不太好用,结果还是出现了重复的元素。

请看看上面的函数,给我一些关于如何纠正它们的建议......

谢谢=)

【问题讨论】:

    标签: list append ocaml


    【解决方案1】:

    如果你使用Set,你只需要两个集合的并集即可。

    如果help_append_list 中的l2 没有重复,则您的函数可以正常工作。

    假设xy可以有自己的重复,顺序无关紧要,你可以使用:

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

    我有一些关于你的函数的 cmets。首先,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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-01
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 2017-11-02
      • 1970-01-01
      相关资源
      最近更新 更多