descript-lang-0.2.0.0: src/Core/Numeric.hs
module Core.Numeric
( readBinary
, readFrac
) where
import Numeric
import Data.Ratio
-- | Reads a binary number (1s and 0s).
readBinary :: (Num a) => ReadS a
readBinary = readInt 2 (`elem` "01") readBit
readBit :: Char -> Int
readBit '0' = 0
readBit '1' = 1
readBit x = error $ "Expected a bit, got " ++ show x
-- | Reads a fraction - @a/b@, where @a@ and @b@ are integers.
readFrac :: ReadS Rational
readFrac str = do
(numer, inter) <- read str
'/' : inter' <- [dropWhile (' ' ==) inter]
(denom, rest) <- read inter'
pure (numer % denom, rest)