2012-04-22 73 views
1

我有一个在我的Ocaml项目中的帮助功能,有助于追加列表到另一个没有元素重复。 例如,附加list x: [d, e, f, g]list y [a, b, c, d],结果应该是[A,B,C,d,E,F,G]Ocaml追加列表到另一个列表没有重复

我写功能是这样的:

(* 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) 
;; 

但这多申”当我使用它时看起来效果不错,结果会出现重复的元素。

请看看上面的功能,并给我如何纠正他们一些建议...

谢谢=)

回答

4

如果使用Set,你只需要两套联盟目的。

如果l2help_append_list没有重复,您的功能正常工作。

假设xy可以有自己的重复,顺序并不重要,你可以使用:

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

我对你的函数的一些意见。首先,find与中的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)