[Haskell-beginners] Re: Iterating through a list of char...

Daniel Fischer daniel.is.fischer at web.de
Thu Apr 29 20:32:35 EDT 2010


Am Freitag 30 April 2010 01:27:54 schrieb Daniel Fischer:
> ----------------------------------------------------------------------
> {-# LANGUAGE BangPatterns #-}
>
> import qualified Data.ByteString.Lazy as L
> import qualified Data.ByteString as S
> import Data.ByteString.Unsafe (unsafeAt)

Oops,

import Data.ByteString.Unsafe (unsafeIndex)

>
> escape :: Word8 -> Word8
> escape = (+150)
>
> normal :: Word8 -> Word8
> normal = (+214)
>
> decodeW :: L.ByteString -> [Word8]
> decodeW = dec False . L.toChunks
>     where
>       dec _ [] = []
>       dec esc (str:more) = go esc 0
>         where
>           !len = S.length str
>           {-# INLINE charAt #-}
>           charAt :: Int -> Word8
>           charAt i = unsafeAt str i

          charAt i = unsafeIndex str i

>           go !b !i
>             | i == len  = dec b more
>             | b         = escape (charAt i) : go False (i+1)
>             | otherwise = case charAt i of
>                             61 -> go True (i+1)
>                             c  -> normal c : go False (i+1)
>
> word8ToChar :: Word8 -> Char
> word8ToChar = toEnum . fromIntegral
>
> decodeC :: L.ByteString -> String
> decodeC = map word8ToChar . decodeW
>
> decodeBS :: L.ByteString -> L.ByteString
> decodeBS = L.pack . decodeW
> ----------------------------------------------------------------------



More information about the Beginners mailing list