Problem #10 Run-length encoding of a list.

March 25, 2008 – 2:40 pm

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);;
 let encode l =
	List.map
		( fun a -> ( List.length a, List.hd a ) )
		( pack l );;
if ((encode ['a';'a';'a';'a';'a';'a';'b';'b';'b';'b';'a';'a';'a';'b';'b';'c';'d';'d';'d';'d';'d';'d';'e']) =
     ([(6,'a');(4,'b');(3,'a');(2,'b');(1,'c');(6,'d');(1,'e');]))
then ( Printf.printf "okn" )
else ( Printf.printf "failedn" );;

It’s easier to reuse code, then reinvent some of the code. This case I used the solution for problem #9 and used the map function to create a new list. The List.map function is incredibly useful. Just ask Google with their Map Reduce

Post a Comment