Commits

Bryan O'Sullivan committed 055c44c

Implement uncons

  • Participants
  • Parent commits 16ff63b

Comments (0)

Files changed (2)

File Data/Text.hs

     , cons
     , snoc
     , append
+    , uncons
     , head
     , last
     , tail
     , zipWith
     ) where
 
-import Prelude (Char, Bool, Int, Maybe, String,
+import Prelude (Char, Bool, Int, Maybe(..), String,
                 Eq, (==), (++), error,
                 Show, showsPrec,
                 Read, readsPrec,
 head t = S.head (stream t)
 {-# INLINE head #-}
 
+-- | /O(1)/ Returns the first character and rest of a 'Text', or
+-- 'Nothing' if empty. Subject to array fusion.
+uncons :: Text -> Maybe (Char, Text)
+uncons t = case S.uncons (stream t) of
+             Just (c, s) -> Just (c, unstream s)
+             Nothing     -> Nothing
+{-# INLINE uncons #-}
+
 -- | /O(n)/ Returns the last character of a 'Text', which must be
 -- non-empty.  Subject to array fusion.
 last :: Text -> Char

File Data/Text/Fusion.hs

     , cons
     , snoc
     , append
+    , uncons
     , head
     , tail
     , last
                       Done -> error "head: Empty list"
 {-# INLINE [0] head #-}
 
--- | /O(n)/ Returns the last character of a Stream Char, which must be non-empty.
+-- | /O(1)/ Returns the first character and remainder of a 'Stream
+-- Char', or 'Nothing' if empty.  Subject to array fusion.
+uncons :: Stream Char -> Maybe (Char, Stream Char)
+uncons (Stream next s0 len) = loop_uncons s0
+    where
+      loop_uncons !s = case next s of
+                         Yield x s1 -> Just (x, Stream next s1 (len-1))
+                         Skip s'    -> loop_uncons s'
+                         Done       -> Nothing
+{-# INLINE [0] uncons #-}
+
+-- | /O(n)/ Returns the last character of a 'Stream Char', which must
+-- be non-empty.
 last :: Stream Char -> Char
 last (Stream next s0 _len) = loop0_last s0
     where