Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell takeWhile + 1

Tags:

haskell

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?

like image 528
Augustin Riedinger Avatar asked Jan 19 '17 12:01

Augustin Riedinger


People also ask

What does TakeWhile do in Haskell?

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.

What is TakeWhile?

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.

What does dropWhile do in Haskell?

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.

What does all do in Haskell?

Examples. Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate.


1 Answers

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.)

like image 133
David Fletcher Avatar answered Sep 17 '22 19:09

David Fletcher