@@ -13,6 +13,7 @@ module WhileEvaluation
1313 ,VarStateWorld
1414 ) where
1515
16+ import Data.List (nub )
1617
1718import WhileParser
1819 (WhileAST (.. )
@@ -64,12 +65,9 @@ evalExpression :: Expression -> VarStateWorld -> Int
6465evalExpression expr state = case expr of
6566 (Constant c) -> c
6667 (Variable varName) -> lookUpVarState varName state
67- (Add exp1 exp2) -> helper (+) [exp1, exp2]
68+ (Add exp1 exp2) -> foldl ( \ acc x -> acc + evalExpression x state) 0 [exp1, exp2]
6869 (Subtract exp1 exp2) -> max 0 $ evalExpression exp1 state - evalExpression exp2 state
69- (Neq exp1 exp2) -> fromEnum $ evalExpression exp1 state /= evalExpression exp2 state
70- where
71- -- helper :: (Int -> Int -> Int) -> [Expression] -> Int
72- helper f = foldl (\ acc x -> f acc (evalExpression x state)) 0
70+ (Neq exp1 exp2) -> fromEnum $ length (nub $ map (`evalExpression` state) [exp1, exp2]) == 2
7371
7472--------------------------------------------------------------------------------
7573
@@ -78,17 +76,22 @@ evalAssignment (Assignment name expr) state = updateVarState name (evalExpressio
7876evalAssignment _ _ = undefined
7977
8078evalWhileExp :: WhileAST -> VarStateWorld -> VarStateWorld
81- evalWhileExp (While expr whileAST) state = helperWhile expr whileAST state
79+ evalWhileExp (While expr whileAST) state = helperWhile expr whileAST state 0
8280evalWhileExp _ _ = undefined
8381
84- -- NOTE maybe check if `evalExpression p state` returns either 0 or 1 ...
85- helperWhile :: Expression -> WhileAST -> VarStateWorld -> VarStateWorld
86- helperWhile p ast state = if evalExpression p state == 1
87- then helperWhile p ast (eval ast state)
88- else state
82+ helperWhile :: Expression -> WhileAST -> VarStateWorld -> Int -> VarStateWorld
83+ helperWhile p ast state maxRec
84+ | maxRec >= getRecursionLimit = error " \n\ESC [91m[RecursionError]\ESC [0m: maximum recursion depth exceeded!"
85+ | evalExpression p state == 1 = helperWhile p ast (eval ast state) (maxRec + 1 )
86+ | otherwise = state
87+ where
88+ -- getRecursionLimit :: Int
89+ getRecursionLimit = 1500
90+
8991
9092evalLoopExp :: WhileAST -> VarStateWorld -> VarStateWorld
9193-- evalLoopExp (Loop exp whileAST) state = (foldr (.) id (replicate (evalExpression exp state) eval))
94+ -- foldr (\_ accState -> evalLoopExp whileAST (eval expr accState)) state [1..evalExpression expr state]
9295evalLoopExp (Loop expr whileAST) state = helperLoop whileAST state (evalExpression expr state)
9396evalLoopExp _ _ = undefined
9497
0 commit comments