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!
Assuming that the list of indices is sorted, like @AndyG says, it will likely help if you keep track of the current index. You thus can implement a function like:
where you need to fill in the
…parts.Here the
gois thus a function that will use recursion to insert elements. The base case (1) is where the list of indices where you want to insert elements is exhausted, in that case we can return the list itself.If the list itself is exhausted, case (2), but there are still items to fill in, you will need to make a list where you repeat
xthe number of items you still have to insert.The last case (3) you have to check how the index
icompares to the first index where you need to insert an elementn. If it is equal, then you will have to insert the elementxand make a recursion (where you should callgo). If the index is greater than the current one, you yield the elementy, and the recurse on the tail of the list and increment the acculator index.