How can I write a takeWhile that would keep the first element that doesn't match the condition?
Example (obviously my example is trickier than this) :
Instead of takeWhile (\× - > x! = 3) [1..10]
to return [1,2]
I need [1,2,3]
.
I thought of (takeWhile myFunc myList) ++ [find myFunc myList]
but it means I need to go through my list 2 times...
Any idea?
takeWhile is a built-in method in Haskell that inspects the original list using a given predicate and returns its elements until the condition is false.
The TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) method tests each element of source by using predicate and yields the element if the result is true . Enumeration stops when the predicate function returns false for an element or when source contains no more elements.
dropWhile drops elements while the condition is true and then stops (returning the remaining elements) once the condition is false. With dropWhile (== 'X') "AXF" the condition is false right away (because 'A' == 'X' is false), so it doesn't drop anything and returns the whole list.
Examples. Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate.
You can use span
or break
.
λ> span (/=3) [1..10]
([1,2],[3,4,5,6,7,8,9,10])
So you can do something like this:
takeWhileInc :: (a -> Bool) -> [a] -> [a]
takeWhileInc p xs = case zs of [] -> error "not found"
(z:_) -> ys ++ [z]
where
(ys, zs) = span p xs
(Or whatever you want to happen when zs
is empty because no 3
was found.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With