Commits

Bryan O'Sullivan  committed 8ce987e

Implement lazy chunksOf.

  • Participants
  • Parent commits b7f3780

Comments (0)

Files changed (2)

File 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]

File 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
     ],