Parsec newbie question

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Parsec newbie question

Patrick LeBoutillier
Hi all,

I'd like to use parsec to parse IP addresses. So far I've written a (tiny)
parser for bytes:

byte :: GenParser Char st Word8
byte = do
         n <- many1 digit
         return (read n)

The function works fine, but it accepts numbers greater than 255.
How do I encapsulate this condition in the parser so that it fails (with en
appropriate error message) in this case?


Thanks a lot,

Patrick

--
=====================
Patrick LeBoutillier
Rosem?re, Qu?bec, Canada
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090831/0508dd4d/attachment.html
Reply | Threaded
Open this post in threaded view
|

Parsec newbie question

Daniel Fischer-4
Am Montag 31 August 2009 19:33:48 schrieb Patrick LeBoutillier:

> Hi all,
>
> I'd like to use parsec to parse IP addresses. So far I've written a (tiny)
> parser for bytes:
>
> byte :: GenParser Char st Word8
> byte = do
>          n <- many1 digit
>          return (read n)
>
> The function works fine, but it accepts numbers greater than 255.
> How do I encapsulate this condition in the parser so that it fails (with en
> appropriate error message) in this case?
>

byte :: GenParser Char st Word8
byte = do
    ds <- many1 digit
    let n :: Integer  -- or Int, if you're not too paranoid
        n = read ds
    if n < 256
      then return (fromIntegral n)
      else fail $ "Number " ++ ds ++ " too large for a byte."

>
> Thanks a lot,
>
> Patrick