是否有一个内置的函数来获取Haskell中列表的所有大小为n的连续子序列? [英] Is there a built-in function to get all consecutive subsequences of size n of a list in Haskell?
本文介绍了是否有一个内置的函数来获取Haskell中列表的所有大小为n的连续子序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我需要一个函数:
gather :: Int - > [a] - > [[a]]
gather n list = ???
其中 collect 3Hello! == [Hel,ell,llo,ol!]
。
我有一个工作实现: / p>
gather :: Int-> [a] - > [[a]]
gather n list =
unfoldr
(\ x - >
if fst x + n> length(snd x)then
没有任何
其他
只需
(
n
(drop
(fst x)
(snd x)),
fst x + 1,snd x)))
(0,list)
我想知道这个语言是否已经有内置的东西?我扫描Data.List但没有看到任何东西。
解决方案 您可以使用
tails
: gather nl = filter((== n)。length)$ map(take n)$ tails l
或使用 takeWhile
而不是过滤器
:
gather nl = takeWhile((== n)。length)$ map(take n)$ tails l
编辑:您可以通过删除最后一个 n $ c $如
聚集n =地图(带n)。 dropLast n。尾巴
其中dropLast n xs = zipWith常量xs(drop n xs)
For example, I need a function:
gather :: Int -> [a] -> [[a]]
gather n list = ???
where gather 3 "Hello!" == ["Hel","ell","llo","ol!"]
.
I have a working implementation:
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)
but I am wondering if there is something already built into the language for this? I scanned Data.List but didn't see anything.
解决方案
You could use tails
:
gather n l = filter ((== n) . length) $ map (take n) $ tails l
or using takeWhile
instead of filter
:
gather n l = takeWhile ((== n) . length) $ map (take n) $ tails l
EDIT: 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屋!
查看全文