是否有内置函数来获取 Haskell 中列表大小为 n 的所有连续子序列? [英] Is there a built-in function to get all consecutive subsequences of size n of a list in Haskell?
本文介绍了是否有内置函数来获取 Haskell 中列表大小为 n 的所有连续子序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我需要一个函数:
For example, I need a function:
gather :: Int -> [a] -> [[a]]
gather n list = ???
where gather 3 "Hello!"== ["Hel","ell","llo","ol!"]
.
我有一个有效的实现:
gather :: Int-> [a] -> [[a]]
gather n list =
unfoldr
(x ->
if fst x + n > length (snd x) then
Nothing
else
Just
(take
n
(drop
(fst x)
(snd x)),
(fst x + 1, snd x)))
(0, list)
但我想知道语言中是否已经为此内置了一些东西?我扫描了 Data.List 但没有看到任何东西.
but I am wondering if there is something already built into the language for this? I scanned Data.List but didn't see anything.
推荐答案
你可以使用tails
:
gather n l = filter ((== n) . length) $ map (take n) $ tails l
或使用 takeWhile
而不是 filter
:
gather n l = takeWhile ((== n) . length) $ map (take n) $ tails l
您可以通过删除从 tails
返回的列表的最后一个 n
元素来删除过滤步骤,如评论中所建议:
You can remove the filter step by dropping the last n
elements of the list returned from tails
as suggested in the comments:
gather n = map (take n) . dropLast n . tails
where dropLast n xs = zipWith const xs (drop n xs)
这篇关于是否有内置函数来获取 Haskell 中列表大小为 n 的所有连续子序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文