Commits

Bryan O'Sullivan committed 0c25917

Implement and test lazy init

Comments (0)

Files changed (2)

Data/Text/Lazy.hs

     , head
     , last
     , tail
-    -- , init
+    , init
     -- , null
     -- , length
 
 head t = S.head (stream t)
 {-# INLINE head #-}
 
+-- | /O(1)/ Returns all characters after the head of a 'Text', which
+-- must be non-empty.  Subject to array fusion.
 tail :: Text -> Text
 tail (Chunk t ts) = chunk (T.tail t) ts
 tail Empty        = emptyError "tail"
     unstream (S.tail (stream t)) = tail t
  #-}
 
+init :: Text -> Text
+init (Chunk t0 ts0) = go t0 ts0
+    where go t (Chunk t' ts) = Chunk t (go t' ts)
+          go t Empty         = chunk (T.init t) Empty
+init Empty = emptyError "init"
+{-# INLINE [1] init #-}
+
+{-# RULES
+"LAZY TEXT init -> fused" [~1] forall t.
+    init t = unstream (S.init (stream t))
+"LAZY TEXT init -> unfused" [1] forall t.
+    unstream (S.init (stream t)) = init t
+ #-}
+
 -- | /O(1)/ Returns the last character of a 'Text', which must be
 -- non-empty.  Subject to array fusion.
 last :: Text -> Char

tests/Properties.hs

 prop_S_tail            = tail   `eqEP` (unpackT . S.tail)
 prop_T_tail            = tail   `eqEP` (unpackT . T.tail)
 prop_TL_tail           = tail   `eqEP` (unpackT . TL.tail)
+prop_S_init            = init   `eqEP` (unpackT . S.init)
 prop_T_init            = init   `eqEP` (unpackT . T.init)
-prop_T_initS           = init   `eqEP` (unpackT . S.unstream . S.init . S.stream)
+prop_TL_init           = init   `eqEP` (unpackT . TL.init)
 prop_T_null            = null   `eqP`  T.null
 prop_T_length          = length `eqP`  T.length
 prop_T_map f           = map f  `eqP`  (unpackT . T.map f)
   ("prop_S_tail", mytest prop_S_tail),
   ("prop_T_tail", mytest prop_T_tail),
   ("prop_TL_tail", mytest prop_TL_tail),
+  ("prop_S_init", mytest prop_S_init),
   ("prop_T_init", mytest prop_T_init),
-  ("prop_T_initS", mytest prop_T_initS),
+  ("prop_TL_init", mytest prop_TL_init),
   ("prop_T_null", mytest prop_T_null),
   ("prop_T_length", mytest prop_T_length),