简体   繁体   中英

Does Haskell have a takeUntil function?

Currently I am using

takeWhile (\x -> x /= 1 && x /= 89) l

to get the elements from a list up to either a 1 or 89. However, the result doesn't include these sentinel values. Does Haskell have a standard function that provides this variation on takeWhile that includes the sentinel in the result? My searches with Hoogle have been unfruitful so far.

Since you were asking about standard functions, no . But also there isn't a package containing a takeWhileInclusive , but that's really simple:

takeWhileInclusive :: (a -> Bool) -> [a] -> [a]
takeWhileInclusive _ [] = []
takeWhileInclusive p (x:xs) = x : if p x then takeWhileInclusive p xs
                                         else []

The only thing you need to do is to take the value regardless whether the predicate returns True and only use the predicate as a continuation factor:

*Main> takeWhileInclusive  (\x -> x /= 20) [10..]
[10,11,12,13,14,15,16,17,18,19,20]

Is span what you want?

matching, rest = span (\x -> x /= 1 && x /= 89) l

then look at the head of rest .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM