Skip to content

Instantly share code, notes, and snippets.

@mitghi
Created March 19, 2023 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitghi/03afb223b6f540e2d37556bceab2d6a7 to your computer and use it in GitHub Desktop.
Save mitghi/03afb223b6f540e2d37556bceab2d6a7 to your computer and use it in GitHub Desktop.
stack machine
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