on master help sign in
Implement lazy chunksOf.

--HG-- extra : convert_revision : e647493f6780b424003112252429a83aa3d102f5

commit41d840797a525771c8e842490407ce1e4ddbf8c8 authorBryan O'Sullivan <bos@serpentine.com> dateSun 16 Aug 2009, 03:49 (17 years ago) parent06eed51
2 files changed+18
Data/Text/Lazy.hs+15 tests/Properties.hs+3
Data/Text/Lazy.hs+15
@@ -115,6 +115,7 @@ module Data.Text.Lazy
115115 -- ** Breaking into many substrings
116116 , split
117117 , splitWith
118+ , chunksOf
118119 -- , breakSubstring
119120
120121 -- ** Breaking into lines and words
@@ -775,6 +776,20 @@ splitWith p (Chunk t0 ts0) = comb [] (T.splitWith p t0) ts0
775776 comb _ [] _ = impossibleError "splitWith"
776777{-# INLINE splitWith #-}
777778
779+-- | /O(n)/ Splits a 'Text' into components of length @k@. The last
780+-- element may be shorter than the other chunks, depending on the
781+-- length of the input. Examples:
782+--
783+-- > chunksOf 3 "foobarbaz" == ["foo","bar","baz"]
784+-- > chunksOf 4 "haskell.org" == ["hask","ell.","org"]
785+chunksOf :: Int64 -> Text -> [Text]
786+chunksOf k = go
787+ where
788+ go t = case splitAt k t of
789+ (a,b) | null a -> []
790+ | otherwise -> a : go b
791+{-# INLINE chunksOf #-}
792+
778793-- | /O(n)/ Breaks a 'Text' up into a list of 'Text's at
779794-- newline 'Char's. The resulting strings do not contain newlines.
780795lines :: Text -> [Text]
tests/Properties.hs+3
@@ -390,6 +390,8 @@ t_chunksOf_same_lengths k = all ((==k) . T.length) . ini . T.chunksOf k
390390t_chunksOf_length k t = len == T.length t || (k <= 0 && len == 0)
391391 where len = L.sum . L.map T.length $ T.chunksOf k t
392392
393+tl_chunksOf k = T.chunksOf k `eq` (map (T.concat . TL.toChunks) . TL.chunksOf (fromIntegral k) . TL.fromChunks . (:[]))
394+
393395t_breakSubstring_isInfixOf s l
394396 = T.isInfixOf s l ==
395397 T.null s || (not . T.null . snd $ C.breakSubstring s l)
@@ -743,6 +745,7 @@ tests = [
743745 testProperty "tl_splitWith" tl_splitWith,
744746 testProperty "t_chunksOf_same_lengths" t_chunksOf_same_lengths,
745747 testProperty "t_chunksOf_length" t_chunksOf_length,
748+ testProperty "tl_chunksOf" tl_chunksOf,
746749 testProperty "t_breakSubstringC" t_breakSubstringC,
747750 testProperty "t_breakSubstring_isInfixOf" t_breakSubstring_isInfixOf
748751 ],