OCaml: Removing duplicates from a list while maintaining order from the right -
i read this thread , find interesting.
i implement remove left function in few minutes:
(* * remove duplicate left: * 1 2 1 3 2 4 5 -> 1 2 3 4 5 * *) let rem_from_left lst = let rec is_member n mlst = match mlst | [] -> false | h::tl -> begin if h=n true else is_member n tl end in let rec loop lbuf rbuf = match rbuf | [] -> lbuf | h::tl -> begin if is_member h lbuf loop lbuf tl else loop (h::lbuf) rbuf end in list.rev (loop [] lst) i know implement is_member map or hashtable make faster, in moment that's not concern.
in case of implementing remove right, can implement list.rev:
(* * remove duplicate right: * 1 2 1 3 2 4 5 -> 1 3 2 4 5 * *) let rem_from_right lst = list.rev (rem_from_left (list.rev lst)) i'm wondering if can implement in way?
instead of accumulating values on way recursing end, can collect values on way up:
let rem_from_right lst = let rec is_member n mlst = match mlst | [] -> false | h::tl -> begin if h=n true else is_member n tl end in let rec loop lbuf = match lbuf | [] -> [] | h::tl -> begin let rbuf = loop tl in if is_member h rbuf rbuf else h::rbuf end in loop lst
Comments
Post a Comment