Commits

Bryan O'Sullivan  committed 2e466f3

Write chunksOf function.

  • Participants
  • Parent commits 7f80783

Comments (0)

Files changed (2)

File Data/Text.hs

     , splitTimes
     , splitChar
     , splitWith
+    , chunksOf
 
     -- ** Breaking into lines and words
     , lines
               where (l, s') = break p s
 {-# 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 :: Int -> Text -> [Text]
+chunksOf k = go
+  where
+    go t = case splitAt k t of
+             (a,b) | null a    -> []
+                   | otherwise -> a : go b
+{-# INLINE chunksOf #-}
+
 -- ----------------------------------------------------------------------------
 -- * Searching
 

File tests/Properties.hs

                  | otherwise = l : loop (tail s')
               where (l, s') = break p s
 
+prop_T_chunksOf_same_lengths k t
+    = all ((==k) . T.length) . ini . T.chunksOf k $ t
+  where ini [] = []
+        ini xs = init xs
+
+prop_T_chunksOf_length k t = let len = L.foldl' f 0 (T.chunksOf k t)
+                             in  len == T.length t || (k <= 0 && len == 0)
+    where f s t = T.length t + s
+
 prop_T_breakSubstring_isInfixOf s l
                      = T.isInfixOf s l ==
                        T.null s || (not . T.null . snd $ T.breakSubstring s l)
   ("prop_TL_split_i", mytest prop_TL_split_i),
   ("prop_T_splitWith", mytest prop_T_splitWith),
   ("prop_TL_splitWith", mytest prop_TL_splitWith),
+  ("prop_T_chunksOf_same_lengths", mytest prop_T_chunksOf_same_lengths),
+  ("prop_T_chunksOf_length", mytest prop_T_chunksOf_length),
   ("prop_T_breakSubstringC", mytest prop_T_breakSubstringC),
   ("prop_T_breakSubstring_isInfixOf", mytest prop_T_breakSubstring_isInfixOf),