From 62e37cd4e2a3d1d6af9dcd9438c6e38c98b7f42d Mon Sep 17 00:00:00 2001 From: Gregor Kleen Date: Tue, 21 Feb 2017 22:32:01 +0100 Subject: Fix bounded numeric parsers --- lib/Postdelay/TimeSpec/Utils.hs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) (limited to 'lib/Postdelay') diff --git a/lib/Postdelay/TimeSpec/Utils.hs b/lib/Postdelay/TimeSpec/Utils.hs index 0bce51a..c49ba7a 100644 --- a/lib/Postdelay/TimeSpec/Utils.hs +++ b/lib/Postdelay/TimeSpec/Utils.hs @@ -60,10 +60,12 @@ sign = label "sign" $ choice [ char '+' $> id boundedNatural :: forall s n m. (Show n, Ord n, Num n, StringParser s m) => Bool -- ^ Require number to be padded with zeroes? -> Interval n -> m n -boundedNatural padded (I.intersection (0 <=..< PosInf) -> bounds) = do - n <- foldl' (\i l -> i * 10 + l) 0 <$> digitN (fromDigit <$> digitChar) "Natural number cotained in: " ++ show bounds - when (not $ n `I.member` bounds) $ fail "Natural number out of bounds" - return n +boundedNatural padded (I.intersection (0 <=..< PosInf) -> bounds) + | I.null bounds = empty + | otherwise = do + n <- foldl' (\i l -> i * 10 + l) 0 <$> digitN (fromDigit <$> digitChar) "Natural number cotained in: " ++ show bounds + when (not $ n `I.member` bounds) $ fail "Natural number out of bounds" + return n where digitN :: m n -> m [n] digitN p @@ -78,9 +80,9 @@ boundedNatural padded (I.intersection (0 <=..< PosInf) -> bounds) = do | otherwise = error "boundedNatural in undefined state" minDigits, maxDigits :: Extended Int - (minDigits, maxDigits) = ( max 1 . fmap digits . I.lowerBound $ close bounds - , fmap digits . I.upperBound $ close bounds - ) + (minDigits, maxDigits) = {- traceShowId -} ( max 1 . fmap digits . I.lowerBound $ close bounds + , fmap digits . I.upperBound $ close bounds + ) where close int | (Finite min, False) <- I.lowerBound' int = close $ interval (Finite $ min + 1, True) (I.upperBound' int) @@ -95,7 +97,8 @@ boundedRational :: forall s m n. (Show n, RealFrac n, StringParser s m) => Bool -- ^ Require number to be padded with zeroes -> Interval n -> m n boundedRational padded (I.intersection (0 <=..< PosInf) -> bounds) - = (+) <$> boundedNatural padded wholeBounds <*> fractional "Nonnegative rational contained in: " ++ show bounds + | I.null bounds = empty + | otherwise = (+) <$> boundedNatural padded wholeBounds <*> fractional "Nonnegative rational contained in: " ++ show bounds where fractional :: m n fractional = reqFractional $ char '.' $> (/ 10) . foldr' (\h t -> h + t / 10) 0 <*> some (fromDigit <$> digitChar) -- cgit v1.2.3