Problem 10

99 Haskell Problems

Problem 10

(*) Run-length encoding of a list. Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.

Example:

* (encode '(a a a a b c c a a d e e e e))
((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))

Example in Haskell:

encode "aaaabccaadeeee"
[(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')]

Solution:

encode :: Eq a => [a] -> [(Int, a)]
encode [] = []
encode x = encodePack (pack x)
encodePack [] = []
encodePack (x:xs) = (length x, head x):encodePack xs

Note: The type signature of encode return a list of tuple (Int, a) as defined.

Use of list comprehension or lambda with map function can shorten the solution. The list comprehension describe the mathematics of creating the list of tuple by taking an element x from the list (pack xs) and use x to create the element of the tuple (length x, head x). The lambda function (\x -> (length x, head x)) take an argument of a list and turn it into a tuple. The map function map this lambda function to each element of (pack xs).

encode xs = [(length x, head x) | x <- pack xs]
encode xs = map (\x -> (length x, head x)) (pack xs)
Advertisements

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 )

Google+ photo

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

Connecting to %s