1

私の 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)
;;

しかし、これを使用するとうまく機能していないように見えますが、まだ重複した要素が表示されていることがわかりました。

上記の関数を見て、それらを修正する方法についていくつか提案してください...

ありがとう=)

4

1 に答える 1

5

を使用する場合Set、目的のために必要なのは 2 つのセットの結合だけです。

l2in にhelp_append_list重複がない場合、関数は正常に動作します。

と が独自の重複を持つ可能性がxありy、順序は関係ないとします。次のように使用できます。

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

あなたの機能についていくつかコメントがあります。まず、List モジュールの関数findと同じです。おそらく学習目的で書きたいので、次のように置き換える必要があります。existsif (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)
于 2012-04-22T20:35:31.967 に答える