I have the following function:
-- xs: list to be changed
-- ws: list of indices where the values will change to 0
replaceAtIndices xs ws = [if (fromJust (elemIndex x xs)) `elem` ws then 0 else x | x <- xs]
The function takes in 2 lists. ws are the indices of the values in xs that I want to change to 0.
For some reason, it works for some cases, and not for others:
*Main> replaceAtIndices [1,2,3,4] [2,3]
[1,2,0,0] — correct
*Main> replaceAtIndices [1,2,3,4] [2]
[1,2,0,4] — correct
*Main> replaceAtIndices [1,1,2,1,3] [3]
[1,1,2,1,3] — SHOULD be [1,1,2,0,3]
Can anyone please explain why this is?
Thanks in advance!
elemIndexreturns the index of the first occurrence of the item in the list, so in the third case it always returns0for the index of1which doesn’t match3so nothing gets replaced.A better way of associating indexes with the items is to use
zip: