on master help sign in
Implement repeat, cycle, iterate for lazy Texts
e0a9fcbRyanGlScott
Data/Text/Lazy.hs+26−1
@@ -125,7 +125,10 @@ module Data.Text.Lazy
125 , mapAccumR
125 , mapAccumR
126
126
127 -- ** Generation and unfolding
127 -- ** Generation and unfolding
128+ , repeat
128 , replicate
129 , replicate
130+ , cycle
131+ , iterate
129 , unfoldr
132 , unfoldr
130 , unfoldrN
133 , unfoldrN
131
134
@@ -218,7 +221,8 @@ import qualified Data.Text.Unsafe as T
218import qualified Data.Text.Internal.Lazy.Fusion as S
221import qualified Data.Text.Internal.Lazy.Fusion as S
219import Data.Text.Internal.Fusion.Types (PairS(..))
222import Data.Text.Internal.Fusion.Types (PairS(..))
220import Data.Text.Internal.Lazy.Fusion (stream, unstream)
223import Data.Text.Internal.Lazy.Fusion (stream, unstream)
221−import Data.Text.Internal.Lazy (Text(..), chunk, empty, foldlChunks, foldrChunks)
224+import Data.Text.Internal.Lazy (Text(..), chunk, empty, foldlChunks,
225+ foldrChunks, smallChunkSize)
222import Data.Text.Internal (firstf, safe, text)
226import Data.Text.Internal (firstf, safe, text)
223import qualified Data.Text.Internal.Functions as F
227import qualified Data.Text.Internal.Functions as F
224import Data.Text.Internal.Lazy.Search (indices)
228import Data.Text.Internal.Lazy.Search (indices)
@@ -918,6 +922,12 @@ mapAccumR f = go
918 go z Empty = (z, Empty)
922 go z Empty = (z, Empty)
919{-# INLINE mapAccumR #-}
923{-# INLINE mapAccumR #-}
920
924
925+-- | @'repeat' x@ is an infinite 'Text', with @x@ the value of every
926+-- element.
927+repeat :: Char -> Text
928+repeat c = let t = Chunk (T.replicate smallChunkSize (T.singleton c)) t
929+ in t
930+
921-- | /O(n*m)/ 'replicate' @n@ @t@ is a 'Text' consisting of the input
931-- | /O(n*m)/ 'replicate' @n@ @t@ is a 'Text' consisting of the input
922-- @t@ repeated @n@ times.
932-- @t@ repeated @n@ times.
923replicate :: Int64 -> Text -> Text
933replicate :: Int64 -> Text -> Text
@@ -929,6 +939,21 @@ replicate n t
929 | otherwise = t : rep (i+1)
939 | otherwise = t : rep (i+1)
930{-# INLINE [1] replicate #-}
940{-# INLINE [1] replicate #-}
931
941
942+-- | 'cycle' ties a finite 'Text' into a circular one, or equivalently,
943+-- the infinite repetition of the original 'Text'.
944+cycle :: Text -> Text
945+cycle Empty = emptyError "cycle"
946+cycle t = let t' = foldrChunks Chunk t' t
947+ in t'
948+
949+-- | @'iterate' f x@ returns an infinite 'Text' of repeated applications
950+-- of @f@ to @x@:
951+--
952+-- > iterate f x == [x, f x, f (f x), ...]
953+iterate :: (Char -> Char) -> Char -> Text
954+iterate f = unfoldr $ \x -> case f x of
955+ !x' -> Just (x', x')
956+
932-- | /O(n)/ 'replicateChar' @n@ @c@ is a 'Text' of length @n@ with @c@ the
957-- | /O(n)/ 'replicateChar' @n@ @c@ is a 'Text' of length @n@ with @c@ the
933-- value of every element. Subject to fusion.
958-- value of every element. Subject to fusion.
934replicateChar :: Int64 -> Char -> Text
959replicateChar :: Int64 -> Char -> Text