I have a help function in my Ocaml project that helps to append a list to another without element duplicate.
For example, append list x: [d, e, f, g] to list y [a, b, c, d], result should be [a, b, c, d, e, f, g]
The function I wrote is like this:
(* 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)
;;
But this dosen’t look like working well when I use it, it turns out to be there’s still duplicate elements appear.
Please take a look at the above functions and give me some suggestion on how to correct them…
Thank you=)
If you use
Set, you only need union of two sets for the purpose.If
l2inhelp_append_listdoesn’t have duplication, your function works fine.Suppose that
xandycould have their own duplication, and the order doesn’t matter, you could use:I have some comments on your functions. First,
findis the same asexistsfunction in List module. You probably want to write it for learning purpose, soif (h = e) then true else ...should be replaced by||:Second,
[h]@l2is an inefficient way to writeh::l2: