Skip to content

Instantly share code, notes, and snippets.

@swatson555
Created March 26, 2023 05:47
Show Gist options
  • Save swatson555/3458ce3d73e7eacc039aa53c661a5fba to your computer and use it in GitHub Desktop.
Save swatson555/3458ce3d73e7eacc039aa53c661a5fba to your computer and use it in GitHub Desktop.
metacircular python calculator
#!/usr/bin/env python3
""" calc.py
To use,
$ ./calc.py "1+2+3+4"
$ 10
Use `chmod +x calc.py` or run the program with `python3 calc.py <program-string>`.
"""
import ast
import sys
def interp(program):
"""
Interpret and evaluate a python program.
"""
def interp_statement (statement):
match statement:
case ast.Expr (value):
return interp_expression(value)
def interp_expression (expr):
match expr:
case ast.Constant (value, kind):
return value
case ast.BinOp (left, op, right):
valuel = interp_expression(left)
valuer = interp_expression(right)
match op:
case ast.Add (): return valuel+valuer
case ast.Sub (): return valuel-valuer
case ast.Mult (): return valuel*valuer
case ast.Div (): return valuel//valuer
match program:
case ast.Module (body, type_ignores):
value = None
for exp in body:
value = interp_statement(exp)
return value
case ast.Expression (body):
return interp_expression(body)
if __name__ == "__main__":
value = interp(ast.parse(sys.argv[1]))
print(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment