从字符串中删除每个第n个元素

Lun*_*nar 7 haskell

如何删除字符串的每个第n个元素?

我猜你会drop以某种方式使用这个功能.

像这样丢弃第一个n,你怎么能改变这个,所以只丢下第n个,然后是第n个,等等,而不是全部?

dropthem n xs = drop n xs
Run Code Online (Sandbox Code Playgroud)

Dan*_*ton 9

简单.取(n-1)个元素,然后跳过1,冲洗并重复.

dropEvery _ [] = []
dropEvery n xs = take (n-1) xs ++ dropEvery n (drop n xs)
Run Code Online (Sandbox Code Playgroud)

或者为了效率而以showS风格

dropEvery n xs = dropEvery' n xs $ []
    where dropEvery' n [] = id
          dropEvery' n xs = (take (n-1) xs ++) . dropEvery n (drop n xs)
Run Code Online (Sandbox Code Playgroud)


Pea*_*ker 5

-- groups is a pretty useful function on its own!
groups :: Int -> [a] -> [[a]]
groups n = map (take n) . takeWhile (not . null) . iterate (drop n)

removeEveryNth :: Int -> [a] -> [a]
removeEveryNth n = concatMap (take (n-1)) . groups n
Run Code Online (Sandbox Code Playgroud)


sha*_*ang 3

remove_every_nth :: Int -> [a] -> [a]
remove_every_nth n = foldr step [] . zip [1..]
    where step (i,x) acc = if (i `mod` n) == 0 then acc else x:acc
Run Code Online (Sandbox Code Playgroud)

该函数的作用如下:

zip [1..]用于索引列表中的所有项目,因此 例如zip [1..] "foo"变为[(1,'f'), (2,'o'), (3,'o')]

然后使用右折叠处理索引列表该右折叠累积索引不能被 整除的每个元素n

这是一个稍长的版本,它基本上执行相同的操作,但避免了额外的内存分配zip [1..]并且不需要计算模数。

remove_every_nth :: Int -> [a] -> [a]
remove_every_nth = recur 1
    where recur _ _ []     = []
          recur i n (x:xs) = if i == n
            then recur 1 n xs
            else x:recur (i+1) n xs
Run Code Online (Sandbox Code Playgroud)

  • 使用“cycle”:“removeEveryNth n = map snd”。过滤器 ((/= n) . fst) . (zip $循环[1..n])` (2认同)