{- |
The functions in this module process the list formally from the end.
Actually they traverse the list from the start and check every element.
This way they are strict in the elements and lazy in the list spline.
Thus you can apply them to infinite lists.
Use these functions if the list is long or the test is cheap.
-}
module Data.List.Reverse.StrictElement where

import Data.Tuple.HT (mapFst, mapSnd, forcePair, )

import Prelude hiding (dropWhile, takeWhile, span, )


{- |
Remove the longest suffix of elements satisfying p.
In contrast to @reverse . dropWhile p . reverse@
this works for infinite lists, too.
-}
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile p =
   foldr (\x xs -> if p x && null xs then [] else x:xs) []

{- |
Alternative version of @reverse . takeWhile p . reverse@.
-}
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile p =
   snd .
   foldr
      (\x xys ->
         (if p x && fst xys then mapSnd (x:) else mapFst (const False)) xys)
      (True, [])

{- |
@span p xs == (dropWhile p xs, takeWhile p xs)@
-}
span :: (a -> Bool) -> [a] -> ([a], [a])
span p =
   forcePair .
   foldr
      (\x xys ->
         (if p x && null (fst xys) then mapSnd else mapFst) (x:) xys)
      ([], [])
