2012-04-22 68 views
1

Ocamlプロジェクトに、重複しない別のリストにリストを追加するのに役立つヘルプ機能があります。例えば 、list y [a, b, c, d]list x: [d, e, f, g]を追加し、結果があるべきである[A、B、C、D、E、F、G]Ocamlリストを重複なしで別のリストに追加する

Iが書いた関数は次のようである:

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

しかしdosen」私はそれを使用するときにうまく動作するように見える、それはまだ重複する要素が表示されることが判明。

あなたがSetを使用する場合は、あなただけのために2セットの結合を必要とする)=

ありがとう...

答えて

4

を上記の機能を見て、私はそれらを修正する方法についていくつかの提案を教えてください目的。

l2help_append_listに重複がない場合、機能は正常に動作します。

xyは独自の重複を持つことができ、および順序は重要ではありません、あなたが使うことができることとします

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

私はあなたの機能のいくつかのコメントがあります。まず、findexistsの機能と同じで、List moduleです。あなたは、おそらくそうif (h = e) then true else ...||に置き換える必要があり、目的を学ぶためにそれを書きたい:

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

第二に、[h]@l2h::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) 
関連する問題