on master help sign in
Implement splitAt
34f6990Bryan O'Sullivan
Data/Text.hs+17−1
@@ -95,7 +95,7 @@ module Data.Text
95 , drop
95 , drop
96 , takeWhile
96 , takeWhile
97 , dropWhile
97 , dropWhile
98− -- , splitAt
98+ , splitAt
99 -- , span
99 -- , span
100 -- , break
100 -- , break
101 -- , group
101 -- , group
@@ -633,6 +633,22 @@ dropWhile p (Text arr off len) = loop off 0
633 unstream (S.dropWhile p (stream t)) = dropWhile p t
633 unstream (S.dropWhile p (stream t)) = dropWhile p t
634 #-}
634 #-}
635
635
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+
636-- | /O(n)/ Return all initial segments of the given 'Text', shortest
652-- | /O(n)/ Return all initial segments of the given 'Text', shortest
637-- first.
653-- first.
638inits :: Text -> [Text]
654inits :: Text -> [Text]
tests/Properties.hs+2
@@ -92,6 +92,7 @@ prop_takeWhile p = L.takeWhile p `eqP` (unpack . T.takeWhile p)
92prop_takeWhileS p = L.takeWhile p `eqP` (unpack . unstream . S.takeWhile p . stream)
92prop_takeWhileS p = L.takeWhile p `eqP` (unpack . unstream . S.takeWhile p . stream)
93prop_dropWhile p = L.dropWhile p `eqP` (unpack . T.dropWhile p)
93prop_dropWhile p = L.dropWhile p `eqP` (unpack . T.dropWhile p)
94prop_dropWhileS p = L.dropWhile p `eqP` (unpack . unstream . S.dropWhile p . stream)
94prop_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)
95prop_inits = L.inits `eqP` (map unpack . T.inits)
96prop_inits = L.inits `eqP` (map unpack . T.inits)
96prop_tails = L.tails `eqP` (map unpack . T.tails)
97prop_tails = L.tails `eqP` (map unpack . T.tails)
97
98
@@ -179,6 +180,7 @@ tests = [
179 ("prop_takeWhileS", mytest prop_takeWhileS),
180 ("prop_takeWhileS", mytest prop_takeWhileS),
180 ("prop_dropWhile", mytest prop_dropWhile),
181 ("prop_dropWhile", mytest prop_dropWhile),
181 ("prop_dropWhileS", mytest prop_dropWhileS),
182 ("prop_dropWhileS", mytest prop_dropWhileS),
183+ ("prop_splitAt", mytest prop_splitAt),
182 ("prop_inits", mytest prop_inits),
184 ("prop_inits", mytest prop_inits),
183 ("prop_tails", mytest prop_tails),
185 ("prop_tails", mytest prop_tails),
184
186