This code is a Parser that parses numbers according to R5RS
.
- #b1001 - binary
- #o2127 - octal
- #h02d - hexadecimal
- #d1231 - decimal
- 3923 - decimal
It is working at the moment, the only problem is the parseNumberBase
. I am really new to haskell, but it does not look very good to me.
- How could I improve it? (readability wise)
- It would also be nice to see a more "idiomatic" approach
import Data.Char (digitToInt)
import Numeric (readInt, readOct, readHex)
import Data.Maybe (listToMaybe, fromJust)
parseNumber :: Parser LispVal
parseNumber = parseNumberBase 'd'
<|> do char '#'
base <- oneOf "bdoh"
parseNumberBase base
-- | Parses a number at a specific base
parseNumberBase :: Char -> Parser LispVal
parseNumberBase 'b' =
do digits <- many1 (oneOf "01")
return $ (Number . fromJust . readBinary) digits
parseNumberBase 'o' =
do digits <- many1 octDigit
return $ Number (fst (readOct digits !! 0))
parseNumberBase 'd' =
do digits <- many1 digit
return $ (Number . read) digits
parseNumberBase 'h' =
do digits <- many1 hexDigit
return $ Number (fst (readHex digits !! 0))
parseNumberBase _ =
error "Wrong number base"
readBinary :: String -> Maybe Integer
readBinary =
fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
Parser
? \$\endgroup\$