Problem #8 Eliminate consecutive duplicates of list elements.

March 19, 2008 – 2:01 am

This problem was a bit harder than usual. A couple of things were learned from doing this problem. Using [] to enclose an a’ type while get rid of type mismatch errors. Another development tip is to build the inner recursive function first and then make the wrapper function.


let compress_list clist =
  let rec rec_compress_list head tail =
   match tail with
   | [] -> []
   | (y::ys) ->  if [y] = [head] then
                   rec_compress_list y ys
                 else
                   [head] @ (rec_compress_list y ys)
 in match clist with
   | [] -> clist
   | (y::ys) -> (rec_compress_list y ys);;

Here are some test cases.


['a';'a';'a';'a';'a';'a';'b';'b';'b';'b';'a';'a';'a';'b';'b';'c';'d';'d';'d';'d';'d';'d';'e'] |> compress_list |> List.iter (printf "[%c]") ;
printf "n";
['a';'b';'b';'b';'b';'a';'a';'a';'b';'b';'c';'d';'d';'d';'d';'d';'d';'e'] |> compress_list |> List.iter (printf "[%c]") ;

–Update

Joel Lanciaux was kind enough to point out a bug. Apparently my function was chopping off the last element. D’oh!

Here is the updated solution


let compress_list clist =
  let rec rec_compress_list head tail =
   match tail with
   | [] -> [head]
   | (y::ys) ->  if [y] = [head] then
                   rec_compress_list y ys
                 else
                   [head] @ (rec_compress_list y ys)
 in match clist with
   | [] -> clist
   | (y::ys) -> (rec_compress_list y ys);;
  1. 3 Responses to “Problem #8 Eliminate consecutive duplicates of list elements.”

  2. This is indeed a pretty crazy problem — I’m going to have to get going on it tonight (although I’m going to try something a little different). I really like how F# can have functions inside functions — that is really nice.

    By Ryan Lanciaux on Mar 19, 2008

  3. Yeah the tricky part learning to use the [] operators.

    By Jesus DeLaTorre on Mar 20, 2008

  4. It is a pity, that I can not participate in discussion now. It is not enough information. But this theme me very much interests.
    I think, that you are not right. Let’s discuss. Write to me in PM.
    It agree, this idea is necessary just by the way
    I suggest you to come on a site, with an information large quantity on a theme interesting you. For myself I have found a lot of the interesting.
    In it something is. Now all is clear, thanks for an explanation.

    By newavtozvuk on May 9, 2010

Post a Comment