[Haskell-cafe] Attoparsec: Limiting Parsers to N Bytes, or Combing Parsers?

Evan Laforge qdunkan at gmail.com
Sat Sep 24 05:23:18 CEST 2011


BTW you probably want 'data Color = Color !Word8 !Word8 !Word8'

On Fri, Sep 23, 2011 at 8:21 PM, Evan Laforge <qdunkan at gmail.com> wrote:
> On Fri, Sep 23, 2011 at 8:04 PM, Michael Craig <mkscrg at gmail.com> wrote:
>> Suppose we want to parse a 24-bit hex color value:
>> input :: ByteString
>> input = "af093c blah blah blah"
>> type Color = (Word8, Word8, Word8)
>>
>> Attoparsec.Char8 exports a nice hexadecimal parser, but it consumes all
>> available hex-flavored input. I'd like to make it consume exactly two bytes,
>> so I could write my color parser like this:
>>
>> color :: Parser Color
>> color = do
>>     r <- hex2
>>     g <- hex2
>>     b <- hex2
>>     return $ Color (r, g, b)
>> hex2 :: Parser Word8
>> hex2 = ???
>>
>> So my question is "how do I write hex2?" I could easily rewrite hexadecimal,
>> but it would be nicer to reuse its hex-handling logic.
>
> If it's easy enough to write inline, might as well do so.  And it's
> fun with Applicative :)
>
> hex2 = (+) <$> ((*16) <$> higit) <*> higit
> higit = subtract (fromEnum '0') <$> satisfy isHexDigit
> color = Color <$> hex2 <*> hex2 <*> hex2
>



More information about the Haskell-Cafe mailing list