]> git.rmz.io Git - my-scheme.git/commitdiff
Parse Numbers
authorSamir Benmendil <me@rmz.io>
Sun, 14 Jan 2018 00:41:31 +0000 (00:41 +0000)
committerSamir Benmendil <me@rmz.io>
Sun, 14 Jan 2018 00:41:31 +0000 (00:41 +0000)
`many1 digit` matches one or more digits. But it's result is actually a
`Parser String`. We need a way to operate on the value inside the `Parser
String` monad. This is where `liftM` comes in.

Another new thing here is the `.` operator which applies the function on
the right to any input of the function on the left. Or in other words it
applies the right function and passes the result to the function on the
left. In this case, `read` is applied to the parsed digits and the
result (of type Integer) is passed to the `Number` constructor of
`LispVal`.

app/Main.hs

index 6fcf6675f175374d22b749097dc06142312b8400..6daf522b2c86598881760fa72c242009d8516092 100644 (file)
@@ -1,4 +1,5 @@
 module Main where
+import Control.Monad
 import Text.ParserCombinators.Parsec hiding (spaces)
 import System.Environment
 
@@ -32,6 +33,9 @@ parseAtom = do
                 "#f" -> Bool False
                 _    -> Atom atom
 
+parseNumber :: Parser LispVal
+parseNumber = liftM (Number . read) $ many1 digit
+
 readExpr :: String -> String
 readExpr input = case parse (spaces >> symbol) "lisp" input of
     Left err -> "No match: " ++ show err