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
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.
zeros() function returns a new array of given shape and type, where the element's value as 0.
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).
intersperse
is made for this. Just import Data.List (intersperse)
, then intersperse 0 yourList
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With