[OCaml]#5 和集合 積集合 差集合 対称差集合

| コメント(0) | トラックバック(0)
数学の集合、つまり重複を許さないリストについて考えてみる。リストの結合演算子"@"では、結合するリストに同じ要素があれば、結合後のリストにはそれが2個でてくる。これを、要素が重複しない、和集合(A∪B)を返してくれるメソッドunionを定義したい。
重複しないようにするには、先頭から順に結合するリストにも同じものが入っているかを調べればよい。同じものが入っているかどうかは、[OCaml]#4 リストとmatch文のcontainを使えばよく

# let rec contain list n =
  match list with
    [] -> false
  | h::t -> if h=n then true
            else contain t n
  ;;

# let rec union a b = 
  match a with
    [] -> b
    | h::t -> if(contain b h) then union t b
                else h::union t b
  ;;

となり、同様に、積集合(A∩B)intersection、差集合(A-B)defference、対称差(A∪B-A∩B)symmetric differenceを定義する。

# let rec intersection a b = 
  match a with
    [] -> []
    | h::t -> if(contain b h) then h :: intersection t b
                else intersection t b
  ;;
# let rec defference a b = 
  match a with
    [] -> []
    | h::t -> if(contain b h) then defference t b
                else h::defference t b
  ;;
# let rec symmetric_defference a b = 
    defference a b @ defference b a
  ;;

となる。

トラックバック(0)

トラックバックURL: http://blog.isocchi.com/MovableType/mt-tb.cgi/181

コメントする

このブログ記事について

このページは、isocchiが2007年10月16日 23:55に書いたブログ記事です。

ひとつ前のブログ記事は「[OCaml]#4 リストとmatch文」です。

次のブログ記事は「[OCaml]#6 今までの改良&powerset(べき集合)」です。

最近のコンテンツはインデックスページで見られます。過去に書かれたものはアーカイブのページで見られます。

ウェブページ

Powered by Movable Type 5.0