如何在Haskell中获取无限列表中的每个第N个元素? [英] How to get every Nth element of an infinite list in Haskell?
本文介绍了如何在Haskell中获取无限列表中的每个第N个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
我的版本使用drop:
每n xs =案例下降(n-1)xs
(y:ys) - > y:every n ys
[] - > []
编辑:这也适用于有限列表。只有无限列表,查尔斯斯图尔特的解决方案略短。
More specifically, how do I generate a new list of every Nth element from an existing infinite list?
E.g. if the list is [5, 3, 0, 1, 8, 0, 3, 4, 0, 93, 211, 0 ...] then getting every 3rd element would result in this list [0,0,0,0,0 ...]
解决方案
My version using drop:
every n xs = case drop (n-1) xs of
(y:ys) -> y : every n ys
[] -> []
Edit: this also works for finite lists. For infinite lists only, Charles Stewart's solution is slightly shorter.
这篇关于如何在Haskell中获取无限列表中的每个第N个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文