module Data.JustParse.Numeric (
decDigit,
hexDigit,
unsignedDecInt,
unsignedDecInt_,
unsignedHexInt,
unsignedHexInt_,
decInt,
decInt_,
hexInt,
hexInt_,
decFloat,
decFloat_,
) where
import Data.JustParse.Combinator
import Data.JustParse.Internal
import qualified Data.JustParse.Char as C
import Control.Monad ( liftM, liftM2 )
import Data.Char ( ord, digitToInt, toUpper, isDigit, isHexDigit )
decDigit :: Stream s Char => Parser s Int
decDigit = liftM digitToInt C.digit
hexDigit :: Stream s Char => Parser s Int
hexDigit = liftM digitToInt C.hexDigit
unsignedDecInt :: Stream s Char => Parser s Int
unsignedDecInt = decDigit >>= g
where
g x =
do
d <- decDigit
g (x*10+d)
<|> return x
unsignedDecInt_ :: Stream s Char => Parser s Int
unsignedDecInt_ = decDigit >>= g
where
g x =
do
d <- decDigit
g (x*10+d)
<||> return x
unsignedHexInt :: Stream s Char => Parser s Int
unsignedHexInt = hexDigit >>= g
where
g x =
do
d <- hexDigit
g (x*16+d)
<|> return x
unsignedHexInt_ :: Stream s Char => Parser s Int
unsignedHexInt_ = hexDigit >>= g
where
g x =
do
d <- hexDigit
g (x*16+d)
<||> return x
decInt :: Stream s Char => Parser s Int
decInt =
do
sign <- optional (oneOf "-+")
num <- unsignedDecInt
case sign of
Just '-' -> return (num)
_ -> return num
decInt_ :: Stream s Char => Parser s Int
decInt_ =
do
sign <- optional (oneOf "-+")
num <- unsignedDecInt_
case sign of
Just '-' -> return (num)
_ -> return num
hexInt :: Stream s Char => Parser s Int
hexInt =
do
sign <- optional (oneOf "-+")
num <- unsignedHexInt
case sign of
Just '-' -> return (num)
_ -> return num
hexInt_ :: Stream s Char => Parser s Int
hexInt_ =
do
sign <- optional (oneOf "-+")
num <- unsignedHexInt_
case sign of
Just '-' -> return (num)
_ -> return num
decFloat :: Stream s Char => Parser s Float
decFloat =
do
sign <- optional (oneOf "-+")
whole <- many1 C.digit
fractional <- option ".0" (liftM2 (:) (C.char '.') (many1 C.digit))
case sign of
Just '-' -> return ((read (whole ++ fractional)))
_ -> return (read (whole ++ fractional))
decFloat_ :: Stream s Char => Parser s Float
decFloat_ =
do
sign <- optional (oneOf "-+")
whole <- many1_ C.digit
fractional <- option_ ".0" (liftM2 (:) (C.char '.') (many1_ C.digit))
case sign of
Just '-' -> return ((read (whole ++ fractional)))
_ -> return (read (whole ++ fractional))