99 Problems in Scala

Just another WordPress.com weblog

P11 (*) Modified run-length encoding.

Posted by rbpasker on April 20, 2009

 def encodeModified[T] (l :List[T]) : List[Any] = {

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

}
| | | | encodeModified: [T](List[T])List[Any]

scala> encodeModified(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
res7: List[Any] = List((4,'a), 'b, (2,'c), (2,'a), 'd, (4,'e))

Leave a comment