Bryan O'Sullivan avatar Bryan O'Sullivan committed 8ce987e

Implement lazy chunksOf.

Comments (0)

Files changed (2)

Data/Text/Lazy.hs

     -- ** Breaking into many substrings
     , split
     , splitWith
+    , chunksOf
     -- , breakSubstring
 
     -- ** Breaking into lines and words
         comb _   []     _            = impossibleError "splitWith"
 {-# INLINE splitWith #-}
 
+-- | /O(n)/ Splits a 'Text' into components of length @k@.  The last
+-- element may be shorter than the other chunks, depending on the
+-- length of the input. Examples:
+--
+-- > chunksOf 3 "foobarbaz"   == ["foo","bar","baz"]
+-- > chunksOf 4 "haskell.org" == ["hask","ell.","org"]
+chunksOf :: Int64 -> Text -> [Text]
+chunksOf k = go
+  where
+    go t = case splitAt k t of
+             (a,b) | null a    -> []
+                   | otherwise -> a : go b
+{-# INLINE chunksOf #-}
+
 -- | /O(n)/ Breaks a 'Text' up into a list of 'Text's at
 -- newline 'Char's. The resulting strings do not contain newlines.
 lines :: Text -> [Text]

tests/Properties.hs

 t_chunksOf_length k t = len == T.length t || (k <= 0 && len == 0)
   where len = L.sum . L.map T.length $ T.chunksOf k t
 
+tl_chunksOf k = T.chunksOf k `eq` (map (T.concat . TL.toChunks) . TL.chunksOf (fromIntegral k) . TL.fromChunks . (:[]))
+
 t_breakSubstring_isInfixOf s l
                      = T.isInfixOf s l ==
                        T.null s || (not . T.null . snd $ C.breakSubstring s l)
       testProperty "tl_splitWith" tl_splitWith,
       testProperty "t_chunksOf_same_lengths" t_chunksOf_same_lengths,
       testProperty "t_chunksOf_length" t_chunksOf_length,
+      testProperty "tl_chunksOf" tl_chunksOf,
       testProperty "t_breakSubstringC" t_breakSubstringC,
       testProperty "t_breakSubstring_isInfixOf" t_breakSubstring_isInfixOf
     ],
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.