2012-04-22 75 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)