我想编写一个函数,根据满足给定属性的项将列表拆分为子列表 p
.我的问题是如何调用该函数。我将在 Haskell 中给出示例,但在 F# 或 ML 中也会出现同样的问题。
split :: (a -> Bool) -> [a] -> [[a]] --- split lists into list of sublists
连接的子列表是原始列表:
concat (split p xss) == xs
每个子列表都满足
initial_p_only p
属性,也就是说 (A) 子列表以满足 p
的元素开始——因此不为空,并且 (B) 没有其他元素满足 p
:initial_p_only :: (a -> Bool) -> [a] -> Bool
initial_p_only p [] = False
initial_p_only p (x:xs) = p x && all (not . p) xs
所以准确地说,
all (initial_p_only p) (split p xss)
如果原始列表中的第一个元素不满足
p
,拆分失败。这个函数需要被调用而不是
split
. 我应该叫它什么??
最佳答案
我相信您所描述的功能是 breakBefore
来自 list-grouping包裹。Data.List.Grouping
:http://hackage.haskell.org/packages/archive/list-grouping/0.1.1/doc/html/Data-List-Grouping.html
ghci> breakBefore even [3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4,6,2,6]
[[3,1],[4,1,5,9],[2],[6,5,3,5],[8,9,7,9,3],[2,3],[8],[4],[6],[2],[6]]
关于haskell - 什么叫拆分列表的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5438558/