Bryan O'Sullivan avatar Bryan O'Sullivan committed c06aa24

Implement and test lazy inits and tails

Comments (0)

Files changed (2)

Data/Text/Lazy.hs

     , break
     , group
     , groupBy
-    -- , inits
-    -- , tails
+    , inits
+    , tails
 
     -- ** Breaking into many substrings
     -- , split
                                 x  = T.unsafeHead t
                                 xs = chunk (T.unsafeTail t) ts
 
+-- | /O(n)/ Return all initial segments of the given 'Text',
+-- shortest first.
+inits :: Text -> [Text]
+inits = (Empty :) . inits'
+  where inits' Empty        = []
+        inits' (Chunk t ts) = L.map (\t' -> Chunk t' Empty) (L.tail (T.inits t))
+                           ++ L.map (Chunk t) (inits' ts)
+
+-- | /O(n)/ Return all final segments of the given 'Text', longest
+-- first.
+tails :: Text -> [Text]
+tails Empty         = Empty : []
+tails ts@(Chunk t ts')
+  | T.length t == 1 = ts : tails ts'
+  | otherwise       = ts : tails (Chunk (T.unsafeTail t) ts')
+
 revChunks :: [T.Text] -> Text
 revChunks = L.foldl' (flip chunk) Empty
 

tests/Properties.hs

 prop_T_groupBy p       = L.groupBy p   `eqP` (map unpackT . T.groupBy p)
 prop_TL_groupBy p      = L.groupBy p   `eqP` (map unpackT . TL.groupBy p)
 prop_T_inits           = L.inits       `eqP` (map unpackT . T.inits)
+prop_TL_inits          = L.inits       `eqP` (map unpackT . TL.inits)
 prop_T_tails           = L.tails       `eqP` (map unpackT . T.tails)
+prop_TL_tails          = L.tails       `eqP` (map unpackT . TL.tails)
 
 prop_T_split_i c       = id `eq` (T.intercalate (T.singleton c) . T.split c)
 
   ("prop_T_groupBy", mytest prop_T_groupBy),
   ("prop_TL_groupBy", mytest prop_TL_groupBy),
   ("prop_T_inits", mytest prop_T_inits),
+  ("prop_TL_inits", mytest prop_TL_inits),
   ("prop_T_tails", mytest prop_T_tails),
+  ("prop_TL_tails", mytest prop_TL_tails),
 
   ("prop_T_split_i", mytest prop_T_split_i),
   ("prop_T_splitWith", mytest prop_T_splitWith),
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.