【问题标题】:haskell - function with lists involving Maybe not workinghaskell - 包含可能不起作用的列表的函数
【发布时间】:2012-10-08 23:45:11
【问题描述】:

我有以下功能:

-- 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 是 xs 中我要更改为 0 的值的索引。

出于某种原因,它适用于某些情况,而不适用于其他情况:

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

谁能解释一下这是为什么?

提前致谢!

【问题讨论】:

  • 我编辑了标题,因为问题与Monad界面无关; Maybe 只是一种数据类型。

标签: list function haskell maybe


【解决方案1】:

elemIndex 返回列表中项目第一次 出现的索引,因此在第三种情况下,它总是返回0 的索引1 不匹配3 所以什么都没有被替换。

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

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

【讨论】:

  • 谢谢!这也摆脱了使用 Monads 的麻烦!
猜你喜欢
  • 2016-05-31
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
相关资源
最近更新 更多