如何编写一个takeWhile来保持第一个与条件不匹配的元素?
示例(显然我的例子比这更棘手):
而不是takeWhile (\× - > x! = 3) [1..10]
回归[1,2]
我需要[1,2,3]
.
我想到了,(takeWhile myFunc myList) ++ [find myFunc myList]
但这意味着我需要通过我的清单2次...
任何的想法?
你可以使用span
或break
.
?> span (/=3) [1..10] ([1,2],[3,4,5,6,7,8,9,10])
所以你可以这样做:
takeWhileInc :: (a -> Bool) -> [a] -> [a] takeWhileInc p xs = case zs of [] -> error "not found" (z:_) -> ys ++ [z] where (ys, zs) = span p xs
(或者无论你想要发生什么zs
,因为没有3
找到它是空的.)
你可以自己动手.
takeWhileOneMore :: (a -> Bool) -> [a] -> [a] takeWhileOneMore p = foldr (\x ys -> if p x then x:ys else [x]) []
比较它
takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile p = foldr (\x ys -> if p x then x:ys else []) []
显式递归对此也没问题.
takeWhileOneMore :: (a -> Bool) -> [a] -> [a] takeWhileOneMore p [] = [] takeWhileOneMore p (x:xs) = if p x then x : takeWhileOneMore p xs else [x]