{- |
The functions in this module process the list from the end.
They do not access elements at the beginning if not necessary.
You can apply the function only to infinite lists.
Use these functions if the list is short and the test is expensive.
-}
module Data.List.Reverse.StrictSpine where

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

import Prelude hiding (dropWhile, takeWhile, span, )


{- |
Like @reverse . List.dropWhile p . reverse@.
-}
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile p =
   foldr (\x xs -> if null xs && p x then [] else x:xs) []

{- |
Like @reverse . List.takeWhile p . reverse@.
-}
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile p =
   snd .
   foldr
      (\x xys ->
         (if fst xys && p x 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 null (fst xys) && p x then mapSnd else mapFst) (x:) xys)
      ([], [])