on master help sign in
Implement lazy takeEnd
commitb51087ad2791a9f60acb126a616553041a9ed513 authorBryan O'Sullivan <bos@serpentine.com> dateFri 7 Mar 2014, 11:44 (13 years ago) parent274d10e
2 files changed+21
Data/Text/Lazy.hs+18 tests/Tests/Properties.hs+3
Data/Text/Lazy.hs+18
@@ -129,6 +129,7 @@ module Data.Text.Lazy
129129
130130 -- ** Breaking strings
131131 , take
132+ , takeEnd
132133 , drop
133134 , dropEnd
134135 , takeWhile
@@ -936,6 +937,23 @@ take i t0 = take' i t0
936937 unstream (S.take n (stream t)) = take n t
937938 #-}
938939
940+-- | /O(n)/ 'takeEnd' @n@ @t@ returns the suffix remaining after
941+-- taking @n@ characters from the end of @t@.
942+--
943+-- Examples:
944+--
945+-- > takeEnd 3 "foobar" == "bar"
946+takeEnd :: Int64 -> Text -> Text
947+takeEnd n t0
948+ | n <= 0 = empty
949+ | otherwise = fromChunks . L.reverse .
950+ takeChunk n . L.reverse . toChunks $ t0
951+ where takeChunk _ [] = []
952+ takeChunk i (t:ts)
953+ | i <= l = [T.takeEnd (fromIntegral i) t]
954+ | otherwise = t : takeChunk (i-l) ts
955+ where l = fromIntegral (T.length t)
956+
939957-- | /O(n)/ 'drop' @n@, applied to a 'Text', returns the suffix of the
940958-- 'Text' after the first @n@ characters, or the empty 'Text' if @n@
941959-- is greater than the length of the 'Text'. Subject to fusion.
tests/Tests/Properties.hs+3
@@ -465,6 +465,8 @@ t_take n = L.take n `eqP` (unpackS . T.take n)
465465t_takeEnd n = (L.reverse . L.take n . L.reverse) `eqP`
466466 (unpackS . T.takeEnd n)
467467tl_take n = L.take n `eqP` (unpackS . TL.take (fromIntegral n))
468+tl_takeEnd n = (L.reverse . L.take (fromIntegral n) . L.reverse) `eqP`
469+ (unpackS . TL.takeEnd n)
468470s_drop n = L.drop n `eqP` (unpackS . S.drop n)
469471s_drop_s m = L.drop n `eqP` (unpackS . S.unstream . S.drop n)
470472 where n = small m
@@ -1064,6 +1066,7 @@ tests =
10641066 testProperty "t_take" t_take,
10651067 testProperty "t_takeEnd" t_takeEnd,
10661068 testProperty "tl_take" tl_take,
1069+ testProperty "tl_takeEnd" tl_takeEnd,
10671070 testProperty "s_drop" s_drop,
10681071 testProperty "s_drop_s" s_drop_s,
10691072 testProperty "sf_drop" sf_drop,