Problem #9 Pack consecutive duplicates of list elements into sublists.

March 20, 2008 – 1:38 pm

#light
let pack plist =
 let rec rec_pack rest packed acc a =
  match rest with
  [] -> ( packed @ [acc] )
  |x::xs ->
           if ( x = a ) then
            ( rec_pack xs packed ( x :: acc ) a)
           else
            ( rec_pack xs ( packed @ [acc] ) [x] x)
 in match plist with
 [] -> []
 | y::ys -> ( rec_pack ys [] [y] y);;
if
( ( pack ["a";"a";"a";"a";"b";"c";"c";"a";"a";"d";"e";"e";"e";"e"] ) = [["a";"a";"a";"a"];["b"];["c";"c"];["a";"a"];["d"];["e";"e";"e";"e"]] )
then
( Printf.printf "okn" )
else
( Printf.printf "failedn" );;

The code has nothing new seen in previous problems but it may be tricky to read. What the inner recursive function is doing is holding the element that RLE is happening in the variable a. It keeps appending a into acc (accumulator) until it sees a different element. Then it takes the sublist and appends into tha variable packed. The variable names may not be great but this gets the job done.

  1. One Response to “Problem #9 Pack consecutive duplicates of list elements into sublists.”

  2. Thank you for your site. I have found here much useful information…

    By john on Nov 6, 2008

Post a Comment