The function has to be like this: insertElemAt :: a -> [Int] -> [a] -> [a]
.
Examples:
insertElemAt 0 [2,5,9] [1..10]
= [1, 0, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 10]
insertElemAt 0 [1,2,4,8] [0,1,0,0,1,1,0,1]
= [0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1]
I only know beginner Haskell (if
with pipeline |
, and recursion), but i tried my hardest to solve this, but it never works. This is my most recent attempt:
insertElemAt x [0] ys = ys
insertElemAt x [1,2] ys = x:x:ys
insertElemAt x [] ys = ys
insertElemAt x xs [] = []
insertElemAt x (n:ns) (y:ys) = y:insertElemAt x (n-1:ns) ys
I also tried something like this, but this just seems to be chaotic, i think the first one is better:
insertElemAt :: a -> [Int] -> [a]-> [a]
insertElemAt x [0] ys = ys
insertElemAt x [1,2] ys = x:x:ys
insertElemAt x (n:ns) (y:ys) = y:insertElemAt x (map reduc (n:ns)) ys
reduc (n:ns) = n-1 : reduc ns
Maybe my patterns aren't good? I tried to write them in a lot of ways.
I also have to be able to work with this function and use it in a function called insertElemsAt (:: [(a, Int)] -> [a] -> [a])
, which has to be a "general" version of the function above. So i have to be able to give in which position what kind of element i want to insert.
Since I can't do the first one, I'm even more lost with this one. Here is the example. I don't know how I could do this with pipeline if
-s and recursion:
insertElemsAt (zip [0,1,1] [2,5,9]) [1..10]
= [1, 0, 2, 3, 1, 4, 5, 6, 1, 7, 8, 9, 10]
insertElemsAt (zip [0,1,1,1] [1,2,4,8]) [0,1,0,0,1,1,0,1]
= [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1]
Could someone explain to me how to do this in the most simple way? Thank you in advance for any help!