on master help sign in
Implement strict takeEnd
commitd70ea12585f80c93cc566a67ca3fc1d4c838ae4b authorBryan O'Sullivan <bos@serpentine.com> dateFri 7 Mar 2014, 09:27 (13 years ago) parentb696eb0
2 files changed+17
Data/Text.hs+14 tests/Tests/Properties.hs+3
Data/Text.hs+14
@@ -122,6 +122,7 @@ module Data.Text
122122
123123 -- ** Breaking strings
124124 , take
125+ , takeEnd
125126 , drop
126127 , dropEnd
127128 , takeWhile
@@ -1018,6 +1019,19 @@ take n t@(Text arr off len)
10181019 unstream (S.take n (stream t)) = take n t
10191020 #-}
10201021
1022+-- | /O(n)/ 'dropEnd' @n@ @t@ returns the suffix remaining after
1023+-- taking @n@ characters from the end of @t@.
1024+--
1025+-- Examples:
1026+--
1027+-- > takeEnd 3 "foobar" == "bar"
1028+takeEnd :: Int -> Text -> Text
1029+takeEnd n t@(Text arr off len)
1030+ | n <= 0 = empty
1031+ | n >= len = t
1032+ | otherwise = text arr (off+i) (len-i)
1033+ where i = iterNEnd n t
1034+
10211035iterNEnd :: Int -> Text -> Int
10221036iterNEnd n t@(Text _arr _off len) = loop (len-1) n
10231037 where loop i !m
tests/Tests/Properties.hs+3
@@ -462,6 +462,8 @@ s_take_s m = L.take n `eqP` (unpackS . S.unstream . S.take n)
462462sf_take p n = (L.take n . L.filter p) `eqP`
463463 (unpackS . S.take n . S.filter p)
464464t_take n = L.take n `eqP` (unpackS . T.take n)
465+t_takeEnd n = (L.reverse . L.take n . L.reverse) `eqP`
466+ (unpackS . T.takeEnd n)
465467tl_take n = L.take n `eqP` (unpackS . TL.take (fromIntegral n))
466468s_drop n = L.drop n `eqP` (unpackS . S.drop n)
467469s_drop_s m = L.drop n `eqP` (unpackS . S.unstream . S.drop n)
@@ -1060,6 +1062,7 @@ tests =
10601062 testProperty "s_take_s" s_take_s,
10611063 testProperty "sf_take" sf_take,
10621064 testProperty "t_take" t_take,
1065+ testProperty "t_takeEnd" t_takeEnd,
10631066 testProperty "tl_take" tl_take,
10641067 testProperty "s_drop" s_drop,
10651068 testProperty "s_drop_s" s_drop_s,