Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 513
Code-Apprentice Avatar asked Mar 18 '14 07:03

Code-Apprentice


Video Answer


2 Answers

Is span what you want?

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

then look at the head of rest.

like image 74
sanityinc Avatar answered Oct 18 '22 20:10

sanityinc


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]
like image 30
Zeta Avatar answered Oct 18 '22 21:10

Zeta