on master help sign in
Implement isPrefixOf
26830b5Bryan O'Sullivan
Data/Text.hs+11−2
@@ -115,7 +115,7 @@ module Data.Text
115 , unwords
115 , unwords
116
116
117 -- * Predicates
117 -- * Predicates
118− -- , isPrefixOf
118+ , isPrefixOf
119 -- , isSuffixOf
119 -- , isSuffixOf
120 -- , isInfixOf
120 -- , isInfixOf
121
121
@@ -143,7 +143,7 @@ module Data.Text
143 , -- sort
143 , -- sort
144 ) where
144 ) where
145
145
146−import Prelude (Char, Bool, Functor(..), Int, Maybe(..), String,
146+import Prelude (Char, Bool(..), Functor(..), Int, Maybe(..), String,
147 Eq, (==), (++), error,
147 Eq, (==), (++), error,
148 Read(..), Show(..),
148 Read(..), Show(..),
149 (&&), (||), (+), (-), (<), (>), (<=), (>=), (.), ($),
149 (&&), (||), (+), (-), (<), (>), (<=), (>=), (.), ($),
@@ -836,5 +836,14 @@ unwords :: [Text] -> Text
836unwords = intercalate (singleton ' ')
836unwords = intercalate (singleton ' ')
837{-# INLINE unwords #-}
837{-# INLINE unwords #-}
838
838
839+isPrefixOf :: Text -> Text -> Bool
840+isPrefixOf a@(Text _ _ alen) b@(Text _ _ blen) = alen <= blen && loop 0 0
841+ where loop !i !j | i >= alen = True
842+ | c == e = loop (i+d) (j+f)
843+ | otherwise = False
844+ where (c,d) = iter a i
845+ (e,f) = iter b j
846+{-# INLINE [1] isPrefixOf #-}
847+
839errorEmptyList :: String -> a
848errorEmptyList :: String -> a
840errorEmptyList fun = error ("Data.Text." ++ fun ++ ": empty list")
849errorEmptyList fun = error ("Data.Text." ++ fun ++ ": empty list")
tests/Properties.hs+4
@@ -140,6 +140,8 @@ prop_words = L.words `eqP` (map unpack . T.words)
140prop_unlines = L.unlines `eq` (unpack . T.unlines . map pack)
140prop_unlines = L.unlines `eq` (unpack . T.unlines . map pack)
141prop_unwords = L.unwords `eq` (unpack . T.unwords . map pack)
141prop_unwords = L.unwords `eq` (unpack . T.unwords . map pack)
142
142
143+prop_isPrefixOf s = L.isPrefixOf s`eqP` T.isPrefixOf (pack s)
144+
143prop_elem c = L.elem c `eqP` T.elem c
145prop_elem c = L.elem c `eqP` T.elem c
144prop_filter p = L.filter p `eqP` (unpack . T.filter p)
146prop_filter p = L.filter p `eqP` (unpack . T.filter p)
145prop_find p = L.find p `eqP` T.find p
147prop_find p = L.find p `eqP` T.find p
@@ -235,6 +237,8 @@ tests = [
235 ("prop_unlines", mytest prop_unlines),
237 ("prop_unlines", mytest prop_unlines),
236 ("prop_unwords", mytest prop_unwords),
238 ("prop_unwords", mytest prop_unwords),
237
239
240+ ("prop_isPrefixOf", mytest prop_isPrefixOf),
241+
238 ("prop_elem", mytest prop_elem),
242 ("prop_elem", mytest prop_elem),
239 ("prop_filter", mytest prop_filter),
243 ("prop_filter", mytest prop_filter),
240 ("prop_find", mytest prop_find),
244 ("prop_find", mytest prop_find),