question about parsing integers and floats with Parsec
Harris, Andrew
Andrew.Harris@jhuapl.edu
Fri, 16 Aug 2002 01:08:03 -0400
Hi -
After a bit of monkeying around, it seems the following parser works
to detect both integers and floats, both positive and negative. I'm sure
you wizards have many better ways of doing this. Anyway here it is for your
amusement:
import Parsec
import qualified ParsecToken as P
import ParsecLanguage (emptyDef)
lexer = P.makeTokenParser emptyDef
integer = P.integer lexer
float = P.float lexer
genericgrab :: Parser (Either Integer Double)
genericgrab = try ( do { n <- char '-'
; f <- float
; return (Right (-f))
}
)
<|> try ( do { f <- float
; return (Right f)
}
)
<|> try ( do { f <- integer
; return (Left f)
}
)
-andrew
> -----Original Message-----
> From: Harris, Andrew [mailto:Andrew.Harris@jhuapl.edu]
> Sent: Thursday, August 15, 2002 6:55 PM
> To: 'haskell-cafe@haskell.org'
> Subject: question about parsing integers and floats with Parsec
>
>
> Hi -
>
> This isn't a pure "Haskell" question, but I'm trying to use the
> Parsec library to parse out space separated numbers, which
> could be integers
> or floats and either positive or negative. I was using the
> "naturalOrFloat"
> lexeme parser from the ParsecToken module, until I realized
> that it doesn't
> seem to handle negative integers. I've been poking with
> trying to pair the
> integer and float lexeme parsers with try() blocks, but I
> ain't no parsing
> expert and am not making good progress.
>
> Any help/hints would be appreciated!
>
> thanks,
> -andrew
>
> ---
> Andrew Harris andrew.harris@jhuapl.edu
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>