Created
March 19, 2023 08:19
-
-
Save mitghi/03afb223b6f540e2d37556bceab2d6a7 to your computer and use it in GitHub Desktop.
stack machine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data Expr = Val Int | Add Expr Expr | |
data Op = EVAL Expr | ADD Int | |
value :: Expr -> Int | |
value e = eval e [] | |
eval :: Expr -> [Op] -> Int | |
eval (Val n) stack = exec stack n | |
eval (Add lexpr rexpr) stack = eval lexpr ((EVAL rexpr):stack) | |
exec :: [Op] -> Int -> Int | |
exec [] n = n | |
exec (EVAL y:stail) n = eval y (ADD n:stail) | |
exec (ADD n:stail) m = exec stail (n+m) | |
main :: IO () | |
main = print $ value (Add ( Add (Val 2) (Val 3)) (Val 4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment