Wednesday, October 14, 2009

P10: Run-length encoding of a list.

The idea is to use above unflatten function to group consecutive duplicates into a list and them map it to length, head pair. Here is the example:
val x = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)
val ulist = unflatten(x)
println(ulist)
println(ulist.map(e=>(e.length,e.head)))

Output:
List(List('a, 'a, 'a, 'a, 'a, 'a), List('b), List('c, 'c), List('d), List('e, 'e, 'e,'e))
List((6,'a), (1,'b), (2,'c), (1,'d), (4,'e))

No comments:

Post a Comment