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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.