99 Problems in Scala

Just another WordPress.com weblog

P10 =- Run-length encoding of a list.

Posted by rbpasker on April 20, 2009


scala> def encode[T] (l :List[T]) : List[(Int, T)] = {

pack(l).map(sublist => (sublist.length, sublist.head))

}
| | | | encode: [T](List[T])List[(Int, T)]

scala> encode(List(‘a, ‘a, ‘a, ‘a, ‘b, ‘c, ‘c, ‘a, ‘a, ‘d, ‘e, ‘e, ‘e, ‘e))

res3: List[(Int, Symbol)] = List((4,’a), (1,’b), (2,’c), (2,’a), (1,’d), (4,’e))

Leave a comment