@@ -39,10 +39,13 @@ module Streamly.Prelude
@@ -82,7 +85,7 @@ import Prelude hiding (filter, drop, dropWhile, take,
82 mapM, mapM_, sequence, all, any,
85 mapM, mapM_, sequence, all, any,
83 sum, product, elem, notElem,
86 sum, product, elem, notElem,
84 maximum, minimum, head, last,
87 maximum, minimum, head, last,
85− length)
88+ tail, length, null, reverse)
86import qualified Prelude
89import qualified Prelude
87import qualified System.IO as IO
90import qualified System.IO as IO
@@ -333,11 +336,26 @@ head m =
333 yield a _ = return (Just a)
336 yield a _ = return (Just a)
334 in (runStream (toStream m)) Nothing stop yield
337 in (runStream (toStream m)) Nothing stop yield
339+-- | Extract all but the first element of the stream, if any.
340+tail :: (Streaming t, Monad m) => t m a -> m (Maybe (t m a))
342+ let stop = return Nothing
343+ yield _ Nothing = return $ Just nil
344+ yield _ (Just t) = return $ Just $ fromStream t
345+ in (runStream (toStream m)) Nothing stop yield
336-- | Extract the last element of the stream, if any.
347-- | Extract the last element of the stream, if any.
337{-# INLINE last #-}
348{-# INLINE last #-}
338last :: (Streaming t, Monad m) => t m a -> m (Maybe a)
349last :: (Streaming t, Monad m) => t m a -> m (Maybe a)
339last = foldl (\_ y -> Just y) Nothing id
350last = foldl (\_ y -> Just y) Nothing id
352+-- | Determine whether the stream is empty.
353+null :: (Streaming t, Monad m) => t m a -> m Bool
355+ let stop = return True
356+ yield _ _ = return False
357+ in (runStream (toStream m)) Nothing stop yield
341-- | Determine whether an element is present in the stream.
359-- | Determine whether an element is present in the stream.
342elem :: (Streaming t, Monad m, Eq a) => a -> t m a -> m Bool
360elem :: (Streaming t, Monad m, Eq a) => a -> t m a -> m Bool
343elem e m = go (toStream m)
361elem e m = go (toStream m)
@@ -362,6 +380,19 @@ notElem e m = go (toStream m)
362length :: (Streaming t, Monad m) => t m a -> m Int
380length :: (Streaming t, Monad m) => t m a -> m Int
363length = foldl (\n _ -> n + 1) 0 id
381length = foldl (\n _ -> n + 1) 0 id
383+-- | Returns the elements of the stream in reverse order.
384+-- The stream must be finite.
385+reverse :: (Streaming t) => t m a -> t m a
386+reverse m = fromStream $ go Nothing (toStream m)
388+ go rev rest = Stream $ \svr stp yld ->
389+ let stop = case rev of
391+ Just str -> runStream str svr stp yld
392+ yield a Nothing = runStream (a `scons` rev) svr stp yld
393+ yield a (Just x) = runStream (go (Just $ a `scons` rev) x) svr stp yld
394+ in runStream rest svr stop yield
365-- XXX replace the recursive "go" with continuation
396-- XXX replace the recursive "go" with continuation
366-- | Determine the minimum element in a stream.
397-- | Determine the minimum element in a stream.
367minimum :: (Streaming t, Monad m, Ord a) => t m a -> m (Maybe a)
398minimum :: (Streaming t, Monad m, Ord a) => t m a -> m (Maybe a)