【问题标题】:haskell drop N'th element in list and replace other list with that indexhaskell 删除列表中的第 N 个元素并用该索引替换其他列表
【发布时间】:2016-11-01 16:07:20
【问题描述】:

我有问题,问题是;

从列表中删除每个第 N 个元素,并将其替换为第二个参数中给出的列表中的元素。

示例;

dropandreplace “abcdefgh” 3 “hgfedcba”

输出:“abhdeggh”

删除和替换 [1,0,3,0,5,0,7,0] 2 [2,4,6,8]

输出:[1,2,3,4,5,6,7,8]

我确实实现了该代码;

dropn :: [Char] -> Int -> [Char]
dropn list n = [ i | (i,c) <- ( zip list [1,2..]), (mod c n) /= 0 ]

但是这段代码是从列表中删除第 N 个元素。如何替换其他列表的元素??

【问题讨论】:

  • 如果给定n,列表参数的长度比不正确,应该怎么办? (例如dropandreplace [dropandreplace [1,0,3,0,5,0,7,0] 2 [2,4,6]
  • 您为实际问题尝试了什么?什么不工作?这些是good question 的必要部分。
  • 给出错误消息,例如“第二个列表没有足够的长度”@mnoronha

标签: list haskell list-comprehension


【解决方案1】:

这是一个使用递归和splitAt 的简单解决方案。

dropandreplace :: [a] -> Int -> [a] -> [a]
dropandreplace xs num (r:rs)
  = case splitAt (num-1) xs of
      (f, _:l) -> f ++ r : dropandreplace l num rs
      (f, _)   -> f -- `xs` if you want to preserve longer list
dropandreplace _ _ _ = []

基本上就是这样,

取第 n 个字符,替换为目标,然后递归。


或其他解决方案:

dropandreplace :: [a] -> Int -> [a] -> [a]
dropandreplace ss num rs = zipWith fromMaybe ss (expand rs)
  where
    expand [] = [] -- `repeat Nothing` if you want to preserve longer list
    expand (x:xs) = replicate (num-1) Nothing ++ Just x : expand xs

【讨论】:

  • 它可以工作,但是如果第二个列表没有足够的长度,则返回缺少的列表,例如; dropandreplace [1,0,3,0,5,0,7,0] 2 [2,4,6] 输出; [1,2,3,4,5,6]
  • 为了解决不均匀的长度方向(来自上面的评论),我们应该为空的第二个列表添加一个错误案例:dropandreplace _ _ [] = error "Replacement list has insufficient size" 在我们的基本案例之前。
  • @CanÇalışkan ,我添加了两个 cmets;如果您想保留更长的列表,请使用它们。
猜你喜欢
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2017-05-12
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多