Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell program to replicate elements in List

Tags:

haskell

I am new to Haskell. I am trying to write a program which given a list as an input replicates each element of list k times, where k = position of element in list.

e.g. replic[5,6,7] gives [[5],[6,6],[7,7,7]].

Another condition is solution has to use map function.

Till now code I have written is :

replic [] = [] 
replic (x:xs) =  map (replicate 2 ) [x] ++ replic xs 

This replicates every element twice as replicate has input parameter 2.

What I need is replicate function should be given input as 1 ,2 ,3 in consecutive calls. So I need a counter. How can I use the counter there or do anything else that will give me position of element?

like image 749
apgp88 Avatar asked Dec 16 '22 17:12

apgp88


1 Answers

Expanding on Satvik, the notation

[1..]

gives you an infinite list of numbers counting up.

The function zip associates allows you to merge two lists into a list of tuples

zip :: [a] -> [b] -> [(a,b)]

for example

> zip [1..] [5,6,7] 
[(1,5),(2,6),(3,7)]

this code associates each value in the list with its position in the list

now

replicate :: Int -> a -> [a]

repeats a value an arbitrary number of times. Given these two components, we can design a simple function

replic xs = map (\(a,b) -> replicate a b) (zip [1..] xs)

which I would write pointfree as

replic :: [a] -> [[a]]
replic = map (uncurry replicate) . zip [1..]

this does exactly what you want

> replic [5,6,7]
[[5],[6,6],[7,7,7]]
like image 117
Philip JF Avatar answered Jan 02 '23 13:01

Philip JF