List haskell-包含可能不起作用的列表的函数

List haskell-包含可能不起作用的列表的函数,list,function,haskell,maybe,List,Function,Haskell,Maybe,我有以下功能: -- 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] [1,2,0,0]--正确 *Main> replaceAtIndices [1,2,3,4] [2] *Main&g

我有以下功能:

-- 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]
[1,2,0,0]--正确

*Main> replaceAtIndices [1,2,3,4] [2]
*Main> replaceAtIndices [1,1,2,1,3] [3]
[1,2,0,4]--正确

*Main> replaceAtIndices [1,2,3,4] [2]
*Main> replaceAtIndices [1,1,2,1,3] [3]
[1,1,2,1,3]——应该是[1,1,2,0,3]

谁能解释一下为什么会这样


提前谢谢

elemIndex
返回列表中项目第一次出现的索引,因此在第三种情况下,它总是为
1
的索引返回
0
,该索引与
3
不匹配,因此不会替换任何内容

将索引与项目关联的更好方法是使用
zip

replaceAtIndices xs ws = [if i `elem` ws then 0 else x | (i, x) <- zip [0..] xs]

replaceAntices xs ws=[如果i`elem`ws则0 else x |(i,x)
elemIndex
返回列表中第一次出现的项的索引,因此在第三种情况下,对于
1
的索引,它总是返回
0
,该索引与
3
不匹配,因此不会被替换

将索引与项目关联的更好方法是使用
zip

replaceAtIndices xs ws = [if i `elem` ws then 0 else x | (i, x) <- zip [0..] xs]

replaceAntices xs ws=[如果i`elem`ws那么0其他x |(i,x)谢谢!这也省去了使用Monad!谢谢!这也省去了使用Monad!我编辑标题是因为问题与Monad接口无关;
可能
只是一个数据类型。我编辑标题是因为问题与Monad接口无关;
可能
只是一个数据类型。