on master help sign in
Implement uncons

--HG-- extra : convert_revision : a4c61ea8be58b75e94f170a0c1d687e6f899c5ab

commita74d560022bb2e7bb4f47ed6a41d557d8b06fdbc authorBryan O'Sullivan <bos@serpentine.com> dateTue 27 Jan 2009, 06:43 (18 years ago) parenta70e3a0
2 files changed+24−2
Data/Text.hs+10−1 Data/Text/Fusion.hs+14−1
Data/Text.hs+10−1
@@ -40,6 +40,7 @@ module Data.Text
4040 , cons
4141 , snoc
4242 , append
43+ , uncons
4344 , head
4445 , last
4546 , tail
@@ -97,7 +98,7 @@ module Data.Text
9798 , zipWith
9899 ) where
99100
100−import Prelude (Char, Bool, Int, Maybe, String,
101+import Prelude (Char, Bool, Int, Maybe(..), String,
101102 Eq, (==), (++), error,
102103 Show, showsPrec,
103104 Read, readsPrec,
@@ -227,6 +228,14 @@ head :: Text -> Char
227228head t = S.head (stream t)
228229{-# INLINE head #-}
229230
231+-- | /O(1)/ Returns the first character and rest of a 'Text', or
232+-- 'Nothing' if empty. Subject to array fusion.
233+uncons :: Text -> Maybe (Char, Text)
234+uncons t = case S.uncons (stream t) of
235+ Just (c, s) -> Just (c, unstream s)
236+ Nothing -> Nothing
237+{-# INLINE uncons #-}
238+
230239-- | /O(n)/ Returns the last character of a 'Text', which must be
231240-- non-empty. Subject to array fusion.
232241last :: Text -> Char
Data/Text/Fusion.hs+14−1
@@ -28,6 +28,7 @@ module Data.Text.Fusion
2828 , cons
2929 , snoc
3030 , append
31+ , uncons
3132 , head
3233 , tail
3334 , last
@@ -241,7 +242,19 @@ head (Stream next s0 _len) = loop_head s0
241242 Done -> error "head: Empty list"
242243{-# INLINE [0] head #-}
243244
244−-- | /O(n)/ Returns the last character of a Stream Char, which must be non-empty.
245+-- | /O(1)/ Returns the first character and remainder of a 'Stream
246+-- Char', or 'Nothing' if empty. Subject to array fusion.
247+uncons :: Stream Char -> Maybe (Char, Stream Char)
248+uncons (Stream next s0 len) = loop_uncons s0
249+ where
250+ loop_uncons !s = case next s of
251+ Yield x s1 -> Just (x, Stream next s1 (len-1))
252+ Skip s' -> loop_uncons s'
253+ Done -> Nothing
254+{-# INLINE [0] uncons #-}
255+
256+-- | /O(n)/ Returns the last character of a 'Stream Char', which must
257+-- be non-empty.
245258last :: Stream Char -> Char
246259last (Stream next s0 _len) = loop0_last s0
247260 where