haskell删除列表中的第N个元素,并用该索引替换其他列表

时间:2016-11-01 16:07:20

标签: list haskell list-comprehension

我有问题,问题是;

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

实施例

dropandreplace“abcdefgh”3“hgfedcba”

输出:“abhdeggh”

dropandreplace [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个元素。我怎样才能替换其他列表的元素?

1 个答案:

答案 0 :(得分:0)

这是一个使用递归和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个字符,替换为target,并递归。

或另一种解决方案:

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