Commits

Bryan O'Sullivan committed 0cf9e87

Implement and test lazy uncons

  • Participants
  • Parent commits 75a88fd

Comments (0)

Files changed (2)

File Data/Text/Lazy.hs

     , cons
     , snoc
     , append
-    -- , uncons
+    , uncons
     -- , head
     -- , last
     -- , tail
 import qualified Data.Text as T
 import qualified Data.Text.Fusion as S
 import qualified Data.Text.Fusion.Internal as S
+import qualified Data.Text.Unsafe as T
 import Data.Text.Lazy.Fusion
 import Data.Text.Lazy.Internal
 
     unstream (S.append (stream t1) (stream t2)) = append t1 t2
  #-}
 
+-- | /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 Empty = Nothing
+uncons (Chunk t ts) =
+    Just (T.unsafeHead t,
+          if T.length t == 1 then ts else Chunk (T.unsafeTail t) ts)
+{-# INLINE uncons #-}
+
 -- | /O(n)/ 'splitAt' @n t@ returns a pair whose first element is a
 -- prefix of @t@ of length @n@, and whose second is the remainder of
 -- the string. It is equivalent to @('take' n t, 'drop' n t)@.

File tests/Properties.hs

 prop_TL_snoc x         = (++ [x]) `eqP` (unpackT . (flip TL.snoc) x)
 prop_T_append s        = (s++)    `eqP` (unpackT . T.append (T.pack s))
 prop_T_appendS s       = (s++)    `eqP` (unpackT . S.unstream . S.append (S.stream (T.pack s)) . S.stream)
+
+uncons (x:xs) = Just (x,xs)
+uncons _      = Nothing
+
 prop_T_uncons s        = uncons   `eqP` (fmap (second unpackT) . T.uncons)
-    where uncons (x:xs) = Just (x,xs)
-          uncons _      = Nothing
-          types         = s :: String
+    where types = s :: String
+prop_TL_uncons s       = uncons   `eqP` (fmap (second unpackT) . TL.uncons)
+    where types = s :: String
 prop_T_head            = head   `eqEP` T.head
 prop_T_last            = last   `eqEP` T.last
 prop_T_lastS           = last   `eqEP` (S.last . S.stream)
   ("prop_T_append", mytest prop_T_append),
   ("prop_T_appendS", mytest prop_T_appendS),
   ("prop_T_uncons", mytest prop_T_uncons),
+  ("prop_TL_uncons", mytest prop_TL_uncons),
   ("prop_T_head", mytest prop_T_head),
   ("prop_T_last", mytest prop_T_last),
   ("prop_T_lastS", mytest prop_T_lastS),