on master help sign in
Implement and test lazy uncons

--HG-- extra : convert_revision : 716cea953f67af09149fd65de5f55b30cb2660c0

commit37ab912d99670f729d99c7901ea29c3843a6d583 authorBryan O'Sullivan <bos@serpentine.com> dateSun 1 Mar 2009, 06:50 (18 years ago) parentea7cc8a
2 files changed+19−4
Data/Text/Lazy.hs+11−1 tests/Properties.hs+8−3
Data/Text/Lazy.hs+11−1
@@ -43,7 +43,7 @@ module Data.Text.Lazy
4343 , cons
4444 , snoc
4545 , append
46− -- , uncons
46+ , uncons
4747 -- , head
4848 -- , last
4949 -- , tail
@@ -155,6 +155,7 @@ import Data.String (IsString(..))
155155import qualified Data.Text as T
156156import qualified Data.Text.Fusion as S
157157import qualified Data.Text.Fusion.Internal as S
158+import qualified Data.Text.Unsafe as T
158159import Data.Text.Lazy.Fusion
159160import Data.Text.Lazy.Internal
160161
@@ -233,6 +234,15 @@ append xs ys = foldrChunks Chunk ys xs
233234 unstream (S.append (stream t1) (stream t2)) = append t1 t2
234235 #-}
235236
237+-- | /O(1)/ Returns the first character and rest of a 'Text', or
238+-- 'Nothing' if empty. Subject to array fusion.
239+uncons :: Text -> Maybe (Char, Text)
240+uncons Empty = Nothing
241+uncons (Chunk t ts) =
242+ Just (T.unsafeHead t,
243+ if T.length t == 1 then ts else Chunk (T.unsafeTail t) ts)
244+{-# INLINE uncons #-}
245+
236246-- | /O(n)/ 'splitAt' @n t@ returns a pair whose first element is a
237247-- prefix of @t@ of length @n@, and whose second is the remainder of
238248-- the string. It is equivalent to @('take' n t, 'drop' n t)@.
tests/Properties.hs+8−3
@@ -113,10 +113,14 @@ prop_T_snoc x = (++ [x]) `eqP` (unpackT . (flip T.snoc) x)
113113prop_TL_snoc x = (++ [x]) `eqP` (unpackT . (flip TL.snoc) x)
114114prop_T_append s = (s++) `eqP` (unpackT . T.append (T.pack s))
115115prop_T_appendS s = (s++) `eqP` (unpackT . S.unstream . S.append (S.stream (T.pack s)) . S.stream)
116+
117+uncons (x:xs) = Just (x,xs)
118+uncons _ = Nothing
119+
116120prop_T_uncons s = uncons `eqP` (fmap (second unpackT) . T.uncons)
117− where uncons (x:xs) = Just (x,xs)
118− uncons _ = Nothing
119− types = s :: String
121+ where types = s :: String
122+prop_TL_uncons s = uncons `eqP` (fmap (second unpackT) . TL.uncons)
123+ where types = s :: String
120124prop_T_head = head `eqEP` T.head
121125prop_T_last = last `eqEP` T.last
122126prop_T_lastS = last `eqEP` (S.last . S.stream)
@@ -290,6 +294,7 @@ tests = [
290294 ("prop_T_append", mytest prop_T_append),
291295 ("prop_T_appendS", mytest prop_T_appendS),
292296 ("prop_T_uncons", mytest prop_T_uncons),
297+ ("prop_TL_uncons", mytest prop_TL_uncons),
293298 ("prop_T_head", mytest prop_T_head),
294299 ("prop_T_last", mytest prop_T_last),
295300 ("prop_T_lastS", mytest prop_T_lastS),