on master help sign in
Implement splitAt

--HG-- extra : convert_revision : 16a5d97abbc8f8e5c058926ca8bc23365129445b

commit34f6990f81a1769cd621f0153b7b428856f9e2e0 authorBryan O'Sullivan <bos@serpentine.com> dateFri 6 Feb 2009, 21:02 (18 years ago) parentbbee394
2 files changed+19−1
Data/Text.hs+17−1 tests/Properties.hs+2
Data/Text.hs+17−1
@@ -95,7 +95,7 @@ module Data.Text
9595 , drop
9696 , takeWhile
9797 , dropWhile
98− -- , splitAt
98+ , splitAt
9999 -- , span
100100 -- , break
101101 -- , group
@@ -633,6 +633,22 @@ dropWhile p (Text arr off len) = loop off 0
633633 unstream (S.dropWhile p (stream t)) = dropWhile p t
634634 #-}
635635
636+-- | /O(n)/ 'splitAt' @n t@ returns a pair whose first element is a
637+-- prefix of @t@ of length @n@ and second element is the remainder of
638+-- the string. It is equivalent to @('take' n t, 'drop' n t)@.
639+splitAt :: Int -> Text -> (Text, Text)
640+splitAt n t@(Text arr off len)
641+ | n <= 0 = (empty, t)
642+ | n >= len = (t, empty)
643+ | otherwise = (Text arr off k, Text arr (off+k) (len-k))
644+ where k = loop off 0
645+ end = off + len
646+ loop !i !count
647+ | i >= end || count >= n = i - off
648+ | otherwise = loop (i+d) (count+1)
649+ where d = iter_ arr i
650+{-# INLINE splitAt #-}
651+
636652-- | /O(n)/ Return all initial segments of the given 'Text', shortest
637653-- first.
638654inits :: Text -> [Text]
tests/Properties.hs+2
@@ -92,6 +92,7 @@ prop_takeWhile p = L.takeWhile p `eqP` (unpack . T.takeWhile p)
9292prop_takeWhileS p = L.takeWhile p `eqP` (unpack . unstream . S.takeWhile p . stream)
9393prop_dropWhile p = L.dropWhile p `eqP` (unpack . T.dropWhile p)
9494prop_dropWhileS p = L.dropWhile p `eqP` (unpack . unstream . S.dropWhile p . stream)
95+prop_splitAt n = L.splitAt n `eqP` ((unpack *** unpack) . T.splitAt n)
9596prop_inits = L.inits `eqP` (map unpack . T.inits)
9697prop_tails = L.tails `eqP` (map unpack . T.tails)
9798
@@ -179,6 +180,7 @@ tests = [
179180 ("prop_takeWhileS", mytest prop_takeWhileS),
180181 ("prop_dropWhile", mytest prop_dropWhile),
181182 ("prop_dropWhileS", mytest prop_dropWhileS),
183+ ("prop_splitAt", mytest prop_splitAt),
182184 ("prop_inits", mytest prop_inits),
183185 ("prop_tails", mytest prop_tails),
184186