2012-10-08 35 views
1

名单,我有以下功能:哈斯克尔 - 功能与涉及也许不工作

-- 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] 

功能发生在2名列表。 WS是我想改变为0

出于某种原因,在XS值的指标,它适用于某些情况下,而不是为别人:

*Main> replaceAtIndices [1,2,3,4] [2,3] 

[1,2,0, 0] - 正确

*Main> replaceAtIndices [1,2,3,4] [2] 

[1,2,0,4] - 正确

*Main> replaceAtIndices [1,1,2,1,3] [3] 

[1,1,2,1,3] - 应该是[1,1 ,2,0,3]

任何人都可以请解释为什么这是?

在此先感谢!

+0

我编辑的标题,因为这个问题已经无关单子接口; '也许'只是一种数据类型。 –

回答

4

elemIndex返回第一出现在列表中的项目的指标,因此,在第三种情况下它总是为1指数不匹配3所以没有被替换返回0

指标与项目相关联的一个更好的办法是使用zip

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

谢谢!这也摆脱了必须使用Monads! – user1670032