Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding zeros between elements in list?

Tags:

list

haskell

I'm trying to change a list in haskell to include 0 between every element. If we have initial list [1..20] then i would like to change it to [1,0,2,0,3..20]

What i thought about doing is actually using map on every function, extracting element then adding it to list and use ++[0] to it but not sure if this is the right approach or not. Still learning haskell so might have errors.

My code:

x = map classify[1..20] 

classify :: Int -> Int 
addingFunction 0 [Int]


addingFunction :: Int -> [a] -> [a]
addingFunction x xs = [a] ++ x ++ xs 
like image 940
STOPIMACODER Avatar asked Oct 17 '19 23:10

STOPIMACODER


People also ask

How do you add zeros to an array?

You can use numpy. pad , which pads default 0 to both ends of the array while in constant mode, specify the pad_width = (0, N) will pad N zeros to the right and nothing to the left: N = 4 np.

What does zeros () do in Python?

zeros() function returns a new array of given shape and type, where the element's value as 0.

How do you stack an array depth wise?

The dstack() is used to stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1).


2 Answers

intersperse is made for this. Just import Data.List (intersperse), then intersperse 0 yourList.

like image 161
Joseph Sible-Reinstate Monica Avatar answered Oct 03 '22 00:10

Joseph Sible-Reinstate Monica


You cannot do this with map. One of the fundamental properties of map is that its output will always have exactly as many items as its input, because each output element corresponds to one input, and vice versa.

There is a related tool with the necessary power, though:

concatMap :: (a -> [b]) -> [a] -> [b]

This way, each input item can produce zero or more output items. You can use this to build the function you wanted:

between :: a -> [a] -> [a]
sep `between` xs = drop 1 . concatMap insert $ xs
  where insert x = [sep, x]

0 `between` [1..10]
[1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10]

Or a more concise definition of between:

between sep = drop 1 . concatMap ((sep :) . pure)
like image 39
amalloy Avatar answered Oct 03 '22 01:10

amalloy