我在第二次在不相关的项目中编写以下函数(首先是XML处理,现在是自定义命令行标记处理),我感觉它应该存在于某个库中,我只是找不到它.它对列表元素进行分组,每个组从谓词为真的元素开始.
有任何更简单的方法吗?
groupStartBy :: (a -> Bool) -> [a] -> [[a]]
groupStartBy pred xs = reverse $ map reverse $ foldl' step [] xs
where
step as x | pred x = [x]:as
step (a:as) x = (x:a):as
step [] x = [[x]]
Run Code Online (Sandbox Code Playgroud)
你可以groupBy这样做:
import Data.List (groupBy)
groupStartBy :: (a -> Bool) -> [a] -> [[a]]
groupStartBy pred = groupBy (const (not . pred))
-- or in point free style: groupStartBy = groupBy . const . (not .)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |