on master help sign in
Add splitTimes function.

--HG-- extra : convert_revision : 7f67bc3fd9bf666d3edd66f7c40d197e8dc9bdc4

commitef424908b204a62ef00166eead5ec5beb71410df authorBryan O'Sullivan <bos@serpentine.com> dateSun 5 Jul 2009, 06:14 (17 years ago) parent9e597d5
1 file changed+34
Data/Text.hs+34
Data/Text.hs+34
@@ -114,6 +114,7 @@ module Data.Text
114114
115115 -- ** Breaking into many substrings
116116 , split
117+ , splitTimes
117118 , splitChar
118119 , splitWith
119120 , breakSubstring
@@ -860,6 +861,39 @@ split pat src0
860861 | otherwise = search (n+1) (unsafeTail s)
861862{-# INLINE split #-}
862863
864+-- | /O(m)*O(n)/ Break a 'Text' into pieces at most @k@ times,
865+-- treating the first 'Text' argument as the delimiter to break on,
866+-- and consuming the delimiter. The last element of the list contains
867+-- the remaining text after the number of times to split has been
868+-- reached. A value of zero or less for @k@ causes no splitting to
869+-- occur.
870+--
871+-- Examples:
872+--
873+-- > splitTimes 0 "//" "a//b//c" == ["a//b//c"]
874+-- > splitTimes 2 ":" "a:b:c:d:e" == ["a","b","c:d:e"]
875+-- > splitTimes 100 "???" "a????b" == ["a","?b"]
876+--
877+-- and
878+--
879+-- > intercalate s . splitTimes k s == id
880+splitTimes :: Int -- ^ Maximum number of times to split
881+ -> Text -- ^ Text to split on
882+ -> Text -- ^ Input text
883+ -> [Text]
884+splitTimes k pat src0
885+ | k <= 0 || l == 0 = [src0]
886+ | otherwise = go k src0
887+ where
888+ l = length pat
889+ go !i src = search 0 src
890+ where
891+ search !n !s
892+ | i == 0 || null s = [src] -- not found or limit reached
893+ | pat `isPrefixOf` s = take n src : go (i-1) (drop l s)
894+ | otherwise = search (n+1) (unsafeTail s)
895+{-# INLINE splitTimes #-}
896+
863897-- | /O(n)/ Splits a 'Text' into components delimited by separators,
864898-- where the predicate returns True for a separator element. The
865899-- resulting components do not contain the separators. Two adjacent