Problem 15

99 Haskell Problems

Problem 15

(**) Replicate the elements of a list a given number of times.

Example:

* (repli '(a b c) 3)
(A A A B B B C C C)

Example in Haskell:

> repli "abc" 3
"aaabbbccc"

Solution:

repli :: [a] -> Int -> [a]
repli [] _ = []
repli x 1 = x
repli (x:xs) n = (repli1 x n) ++ (repli xs n)

repli1 :: a -> Int -> [a]
repli1 x 0 = []
repli1 x n = [x] ++ (repli1 x (n-1))

A simpler way is to use the function replicate and concatMap as shown in the solution.

repli :: [a] -> Int -> [a]
repli xs n = concatMap (replicate n) xs

The function replicate takes an Int, n and an element, x and duplicate the element n times. By giving replicate function only an argument n, we created a new function that takes an element x  and duplicate it n time. We can compare the type of replicate and (replicate 2) to see the different.

> :t replicate
replicate :: Int -> a -> [a]
> :t (replicate 2)
(replicate 2) :: a -> [a]
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