playground/coq/union.v

32 lines
849 B
Coq

Require List.
(* By the way, this function is a good example to illustrate
the difference between foldl and foldr... *)
Definition setify (l: list nat): list nat :=
List.fold_left (fun acc x =>
if (List.existsb (fun a => Nat.eqb x a) acc) then acc
else (List.cons x acc)
) l List.nil.
(* Not caring about efficiency here... *)
Definition union (a b: list nat): list nat :=
let aset := setify a in
List.fold_left (fun acc y =>
if (List.existsb (fun x => Nat.eqb x y) acc) then acc
else (List.cons y acc)
) b aset.
(******************** Trying out... ********************)
Require Import List.
Import ListNotations.
Compute setify [0;0;0].
(* = [0] : list nat *)
Compute setify [0;1;1;2;2;2;3;3;3;3].
(* = [3; 2; 1; 0] : list nat *)
Compute union [0;1;1;2;2;2;3;3;3;3] [1;1;4;4].
(* = [4; 3; 2; 1; 0] : list nat *)