on master help sign in
Write chunksOf function.
83b9294Bryan O'Sullivan
Data/Text.hs+15
@@ -118,6 +118,7 @@ module Data.Text
118 , splitTimes
118 , splitTimes
119 , splitChar
119 , splitChar
120 , splitWith
120 , splitWith
121+ , chunksOf
121
122
122 -- ** Breaking into lines and words
123 -- ** Breaking into lines and words
123 , lines
124 , lines
@@ -910,6 +911,20 @@ splitWith p t = loop t
910 where (l, s') = break p s
911 where (l, s') = break p s
911{-# INLINE splitWith #-}
912{-# INLINE splitWith #-}
912
913
914+-- | /O(n)/ Splits a 'Text' into components of length @k@. The last
915+-- element may be shorter than the other chunks, depending on the
916+-- length of the input. Examples:
917+--
918+-- > chunksOf 3 "foobarbaz" == ["foo","bar","baz"]
919+-- > chunksOf 4 "haskell.org" == ["hask","ell.","org"]
920+chunksOf :: Int -> Text -> [Text]
921+chunksOf k = go
922+ where
923+ go t = case splitAt k t of
924+ (a,b) | null a -> []
925+ | otherwise -> a : go b
926+{-# INLINE chunksOf #-}
927+
913-- ----------------------------------------------------------------------------
928-- ----------------------------------------------------------------------------
914-- * Searching
929-- * Searching
915
930
tests/Properties.hs+11
@@ -281,6 +281,15 @@ splitWith p xs = loop xs
281 | otherwise = l : loop (tail s')
281 | otherwise = l : loop (tail s')
282 where (l, s') = break p s
282 where (l, s') = break p s
283
283
284+prop_T_chunksOf_same_lengths k t
285+ = all ((==k) . T.length) . ini . T.chunksOf k $ t
286+ where ini [] = []
287+ ini xs = init xs
288+
289+prop_T_chunksOf_length k t = let len = L.foldl' f 0 (T.chunksOf k t)
290+ in len == T.length t || (k <= 0 && len == 0)
291+ where f s t = T.length t + s
292+
284prop_T_breakSubstring_isInfixOf s l
293prop_T_breakSubstring_isInfixOf s l
285 = T.isInfixOf s l ==
294 = T.isInfixOf s l ==
286 T.null s || (not . T.null . snd $ T.breakSubstring s l)
295 T.null s || (not . T.null . snd $ T.breakSubstring s l)
@@ -513,6 +522,8 @@ tests = [
513 ("prop_TL_split_i", mytest prop_TL_split_i),
522 ("prop_TL_split_i", mytest prop_TL_split_i),
514 ("prop_T_splitWith", mytest prop_T_splitWith),
523 ("prop_T_splitWith", mytest prop_T_splitWith),
515 ("prop_TL_splitWith", mytest prop_TL_splitWith),
524 ("prop_TL_splitWith", mytest prop_TL_splitWith),
525+ ("prop_T_chunksOf_same_lengths", mytest prop_T_chunksOf_same_lengths),
526+ ("prop_T_chunksOf_length", mytest prop_T_chunksOf_length),
516 ("prop_T_breakSubstringC", mytest prop_T_breakSubstringC),
527 ("prop_T_breakSubstringC", mytest prop_T_breakSubstringC),
517 ("prop_T_breakSubstring_isInfixOf", mytest prop_T_breakSubstring_isInfixOf),
528 ("prop_T_breakSubstring_isInfixOf", mytest prop_T_breakSubstring_isInfixOf),
518
529