数学の集合、つまり重複を許さないリストについて考えてみる。リストの結合演算子"@"では、結合するリストに同じ要素があれば、結合後のリストにはそれが2個でてくる。これを、要素が重複しない、和集合(A∪B)を返してくれるメソッドunionを定義したい。
重複しないようにするには、先頭から順に結合するリストにも同じものが入っているかを調べればよい。同じものが入っているかどうかは、[OCaml]#4 リストとmatch文のcontainを使えばよく
となり、同様に、積集合(A∩B)intersection、差集合(A-B)defference、対称差(A∪B-A∩B)symmetric differenceを定義する。
となる。
重複しないようにするには、先頭から順に結合するリストにも同じものが入っているかを調べればよい。同じものが入っているかどうかは、[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
;;
となる。

コメントする