问题描述
我猜你会使用 drop
函数以某种方式。
像这样放下第一个n,你怎么改变它,所以只有第n个,然后是第n个,所以而不是全部?
dropthem n xs =下降n xs
remove_every_nth :: Int - > [a] - > [a]
remove_every_nth n = foldr步骤[]。 zip [1 ..]
其中step(i,x)acc = if(i`mod` n)== 0 then acc else x:acc
以下是函数的作用:
zip [1 ..]
用于索引列表中的所有项目,例如 zip [1 ..]foo
变成 [(1,'f'),(2,'o'),(3,' o')]
。
然后使用,它累积了索引不能被 n
整除的所有元素。
这个稍微长一点的版本基本上是一样的,但是避免了来自 zip [1 ..] $ c的额外内存分配
remove_every_nth :: Int - > [a] - > [a] $ c $并且不需要计算模数。
remove_every_nth = recur 1
where recur _ _ [] = []
recur in(x:xs)= if i == n
then recur 1 n xs
else x:recur(i + 1)n xs
How can you remove every nth element of a string?
I'm guessing you would use the drop
function in some kind of way.
Like this drops the first n, how can you change this so only drops the nth, and then the nth after that, and so on, rather than all?
dropthem n xs = drop n xs
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
Here's what the function does:
zip [1..]
is used to index all items in the list, so e.g. zip [1..] "foo"
becomes [(1,'f'), (2,'o'), (3,'o')]
.
The indexed list is then processed with a right fold which accumulates every element whose index is not divisible by n
.
Here's a slightly longer version that does essentially the same thing, but avoids the extra memory allocations from zip [1..]
and doesn't need to calculate modulus.
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
这篇关于从字符串中删除每个第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!