例如,我需要一个函数:
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 但没有看到任何内容。
你可以使用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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)