module Data.JustParse.Numeric (
decFloat,
decFloat_,
decInt,
decInt_,
hexInt,
hexInt_
) where
import Data.JustParse.Combinator
import Data.JustParse.Internal
import Data.JustParse.Char
import Control.Monad ( liftM, liftM2 )
import Data.Char ( ord, digitToInt, toUpper, isDigit, isHexDigit )
decInt :: Stream s Char => Parser s Int
decInt =
do
sign <- optional (oneOf "-+")
num <- liftM read (many1 digit)
case sign of
Just '-' -> return (num)
_ -> return num
decInt_ :: Stream s Char => Parser s Int
decInt_ =
do
sign <- optional (oneOf "-+")
num <- liftM read (many1_ digit)
case sign of
Just '-' -> return (num)
_ -> return num
decFloat :: Stream s Char => Parser s Float
decFloat =
do
sign <- optional (oneOf "-+")
whole <- many1 digit
fractional <- option ".0" (liftM2 (:) (char '.') (many1 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_ digit
fractional <- option_ ".0" (liftM2 (:) (char '.') (many1_ digit))
case sign of
Just '-' -> return ((read (whole ++ fractional)))
_ -> return (read (whole ++ fractional))
hexInt :: Stream s Char => Parser s Int
hexInt =
do
sign <- optional (oneOf "-+")
num <- liftM (f . reverse) (many1 hexDigit)
case sign of
Just '-' -> return (num)
_ -> return num
where
f [] = 0
f (x:xs)
| isDigit x = digitToInt x + 16 * f xs
| otherwise = ord (toUpper x) ord 'A' + 16 * f xs
hexInt_ :: Stream s Char => Parser s Int
hexInt_ =
do
sign <- optional (oneOf "-+")
num <- liftM (f . reverse) (many1_ hexDigit)
case sign of
Just '-' -> return (num)
_ -> return num
where
f [] = 0
f (x:xs)
| isDigit x = digitToInt x + 16 * f xs
| otherwise = ord (toUpper x) ord 'A' + 16 * f xs