1

I have two arrays of the following types:

a :: IOArray Word16 Word16
b :: [Word16]

and I want a function copyAtPositionI that copies all the elements of array b into array a beginning at the ith index of array a. It can be assumed that the index will not be such that it attempts to copy elements out of the bounds of the array a.

The function should be of the following type:

copyAtPositionI :: IOArray Word16 Word16 -> [Word16] -> Word16 -> IO ()

For example (this is not Haskell),

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [10, 11, 12, 13]

copyAtPositionI a b 3 should result in a being equal to [1, 2, 3, 10, 11, 12, 13, 8, 9]

I did not find any functions in the Data.Array.IO package that does exactly what I want. I only found the function writeArray in the Data.Array.MArray package but I do not know how to execute the function for every element in the array b.

2
  • 1
    Sounds like you just need to mapM_ an insertion action over your list b. Commented Apr 2, 2018 at 20:43
  • Could you be more specific please? I'm having a hard time trying to understand how to apply it, using an index. Commented Apr 2, 2018 at 20:50

1 Answer 1

6

You can use zipWithM_:

copyAtPositionI mut imm i = zipWithM_ (writeArray mut) [i..] imm

If you didn't have it, you could implement it in a pretty straightforward way:

zipWithM_ f (x:xs) (y:ys) = f x y >> zipWithM_ f xs ys
zipWithM_ f _ _ = return ()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.