Haskell program to replicate items in a list

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

eg. replic[5,6,7] gives [[5],[6,6],[7,7,7]] .

Another condition is that the solution must use the map function.

The code so far written by me:

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

This repeats each item twice since replication has input parameter 2 .

I need the replicate function to be entered as 1 ,2 ,3 in consecutive calls. So I need a counter. How can I use a counter there or do something else that will give me the position of the element?

+4
source share
3 answers

Expanding to Satvik, the notation

 [1..] 

gives you an endless list of number counts.

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

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

eg

 > 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 the value an arbitrary number of times. Given these two components, we can create a simple function

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

which I would write without meaning as

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

it does exactly what you want

 > replic [5,6,7] [[5],[6,6],[7,7,7]] 
+8
source

There are many ways to do this.

Here is a solution similar to what you were trying to do. The zipping list box [1..] gives you the counter you like.

 replic = repl . zip [1..] repl [] = [] repl ((x,y):xs) = (replicate xy) : (repl xs) 

Another solution using only map

 replic = map f . zip [1..] where f (c,l) = replicate cl 

If you don't like the idea of ​​using zip , you can also use mapAccumL

 import Data.List replic = snd . mapAccumL f 1 where fav = (a+1,replicate av) 
+3
source

Usually you write:

 replic = zipWith replicate [1..] 

Now you can write your own zipWith yourself using map :

 zipWith' f xs ys = map (uncurry f) $ zip xs ys 

Note that you do not need an index, for example

 import Data.List replic xs = reverse $ transpose (tail $ inits $ reverse xs) 

You can do something similar with map using explicit recursion:

 replic = f . map return where f [] = [] f (x:xs) = x : f (map (\(x:xs) -> x:x:xs) xs) 
+1
source

Source: https://habr.com/ru/post/1443147/


All Articles