on master help sign in
Implement lazy takeEnd
b51087aBryan O'Sullivan
Data/Text/Lazy.hs+18
@@ -129,6 +129,7 @@ module Data.Text.Lazy
129
129
130 -- ** Breaking strings
130 -- ** Breaking strings
131 , take
131 , take
132+ , takeEnd
132 , drop
133 , drop
133 , dropEnd
134 , dropEnd
134 , takeWhile
135 , takeWhile
@@ -936,6 +937,23 @@ take i t0 = take' i t0
936 unstream (S.take n (stream t)) = take n t
937 unstream (S.take n (stream t)) = take n t
937 #-}
938 #-}
938
939
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+
939-- | /O(n)/ 'drop' @n@, applied to a 'Text', returns the suffix of the
957-- | /O(n)/ 'drop' @n@, applied to a 'Text', returns the suffix of the
940-- 'Text' after the first @n@ characters, or the empty 'Text' if @n@
958-- 'Text' after the first @n@ characters, or the empty 'Text' if @n@
941-- is greater than the length of the 'Text'. Subject to fusion.
959-- 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)
465t_takeEnd n = (L.reverse . L.take n . L.reverse) `eqP`
465t_takeEnd n = (L.reverse . L.take n . L.reverse) `eqP`
466 (unpackS . T.takeEnd n)
466 (unpackS . T.takeEnd n)
467tl_take n = L.take n `eqP` (unpackS . TL.take (fromIntegral n))
467tl_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)
468s_drop n = L.drop n `eqP` (unpackS . S.drop n)
470s_drop n = L.drop n `eqP` (unpackS . S.drop n)
469s_drop_s m = L.drop n `eqP` (unpackS . S.unstream . S.drop n)
471s_drop_s m = L.drop n `eqP` (unpackS . S.unstream . S.drop n)
470 where n = small m
472 where n = small m
@@ -1064,6 +1066,7 @@ tests =
1064 testProperty "t_take" t_take,
1066 testProperty "t_take" t_take,
1065 testProperty "t_takeEnd" t_takeEnd,
1067 testProperty "t_takeEnd" t_takeEnd,
1066 testProperty "tl_take" tl_take,
1068 testProperty "tl_take" tl_take,
1069+ testProperty "tl_takeEnd" tl_takeEnd,
1067 testProperty "s_drop" s_drop,
1070 testProperty "s_drop" s_drop,
1068 testProperty "s_drop_s" s_drop_s,
1071 testProperty "s_drop_s" s_drop_s,
1069 testProperty "sf_drop" sf_drop,
1072 testProperty "sf_drop" sf_drop,