gpt4 book ai didi

haskell - 是否有内置函数可以获取 Haskell 中列表的所有大小为 n 的连续子序列?

转载 作者:行者123 更新时间:2023-12-04 16:27:16 25 4
gpt4 key购买 nike

例如,我需要一个函数:

gather :: Int -> [a] -> [[a]]
gather n list = ???

在哪里 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 但什么也没看到。

最佳答案

您可以使用 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

编辑:您可以通过删除最后一个 n 来删除过滤器步骤从 tails 返回的列表元素正如评论中所建议的:
gather n = map (take n) . dropLast n . tails
where dropLast n xs = zipWith const xs (drop n xs)

关于haskell - 是否有内置函数可以获取 Haskell 中列表的所有大小为 n 的连续子序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24599875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com