Added cons expression

This commit is contained in:
Ivy 2021-01-30 14:55:22 +01:00
parent 438db74148
commit d355a5db8a
4 changed files with 19 additions and 3 deletions

View File

@ -14,10 +14,11 @@ base = M.fromList [
] ]
eval :: Env -> Expr -> (Env, Expr) eval :: Env -> Expr -> (Env, Expr)
eval env (IntE x) = (env, IntE x) eval env i@(IntE x) = (env, i)
eval env (VarE v) = (M.insert v nExpr nEnv, nExpr) eval env (VarE v) = (M.insert v nExpr nEnv, nExpr)
where (nEnv, nExpr) = eval env $ env M.! v where (nEnv, nExpr) = eval env $ env M.! v
eval env (SetE v expr) = (M.insert v expr env, NilE) eval env (SetE v expr) = (M.insert v expr env, NilE)
eval env c@(ConsE _ _) = (env, c)
eval env NilE = (env, NilE) eval env NilE = (env, NilE)
--apply :: Proc -> Args -> Expr --apply :: Proc -> Args -> Expr

View File

@ -4,6 +4,7 @@ data Expr = IntE Integer
| VarE String | VarE String
| ProcedureE String [Expr] | ProcedureE String [Expr]
| SetE String Expr | SetE String Expr
| ConsE Expr Expr
| NilE deriving (Show) | NilE deriving (Show)
-- instance Show Expr where -- instance Show Expr where

View File

@ -29,5 +29,5 @@ rightParenT = char ')' >> return RightParenT
symbolT :: GenParser Char st Token symbolT :: GenParser Char st Token
symbolT = do symbolT = do
var <- map toLower <$> many1 (letter <|> oneOf "+-*/!|@#$~%&/=<>") var <- map toLower <$> many1 (letter <|> oneOf "+-*/\\!|@#$~%&/=<>")
return $ SymbolT var return $ SymbolT var

View File

@ -20,7 +20,7 @@ expressionFromTokensEOF = do
expressionFromTokens :: GenParser Token st Expr expressionFromTokens :: GenParser Token st Expr
expressionFromTokens = do expressionFromTokens = do
expr <- intE <|> try setE <|> try nilE <|> varE <|> procedureE expr <- intE <|> try setE <|> try nilE <|> try consE <|> varE <|> procedureE
return expr return expr
intE :: GenParser Token st Expr intE :: GenParser Token st Expr
@ -36,6 +36,15 @@ procedureE = do
_ <- parseRightParenT _ <- parseRightParenT
return $ ProcedureE p args return $ ProcedureE p args
consE :: GenParser Token st Expr
consE = do
_ <- parseLeftParenT
_ <- parseConsT
expr1 <- expressionFromTokens
expr2 <- expressionFromTokens
_ <- parseRightParenT
return $ ConsE expr1 expr2
varE :: GenParser Token st Expr varE :: GenParser Token st Expr
varE = do varE = do
(SymbolT var) <- parseSymbolT (SymbolT var) <- parseSymbolT
@ -78,6 +87,11 @@ parseNilT = satisfyT isNilT
where isNilT (SymbolT "nil") = True where isNilT (SymbolT "nil") = True
isNilT _ = False isNilT _ = False
parseConsT :: GenParser Token st Token
parseConsT = satisfyT isConsT
where isConsT (SymbolT "cons") = True
isConsT _ = False
parseSymbolT :: GenParser Token st Token parseSymbolT :: GenParser Token st Token
parseSymbolT = satisfyT isSymbolT parseSymbolT = satisfyT isSymbolT
where isSymbolT (SymbolT _) = True where isSymbolT (SymbolT _) = True