Last active
October 10, 2022 05:22
-
-
Save cmhobbs/c5779696067ae4034f1f3bc0fc7029de to your computer and use it in GitHub Desktop.
a dumb calculator in python with a hy port
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
; direct port of rpn.py | |
; this could be a lot more lispy and it would be fun to | |
; explore hyrule here, so maybe that's step 2 and 3? | |
(import operator) | |
; two spaces to separate assignment here is kinda tricky | |
(setv | |
ops {"+" operator.add "-" operator.sub "*" operator.mul "/" operator.truediv} | |
stack []) | |
(while True | |
(setv n (input)) | |
(if (in n ops) | |
(do | |
(setv | |
y (int (.pop stack)) | |
x (int (.pop stack)) | |
z ((get ops n) x y)) | |
(.append stack z) ; this syntax is kinda yucky, oop in functional | |
(print "result: " z) | |
(print "stack: " stack)) | |
(do | |
(.append stack n) | |
(print "stack: " stack)))) |
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
# simple RPN calculator with a pretty big stack. we're not sanitizing | |
# any input or worrying about state, this is just an experiment | |
# | |
# i'm using the operator library here to play with imports and external | |
# calls when porting this to hy | |
import operator | |
ops = { | |
'+': operator.add, | |
'-': operator.sub, | |
'*': operator.mul, | |
'/': operator.truediv | |
} | |
stack = [] | |
while True: | |
n = input() | |
# if our i"n"put is an operator, pop the last two items off | |
# the list representing our stack and perform the related | |
# operation on them, storing the result back onto the end of | |
# the stack. | |
if n in ops: | |
y,x = stack.pop(),stack.pop() # reversed because RPN... | |
z = ops[n](x,y) | |
stack.append(z) | |
print(f"result: {z}") | |
print(f"stack: {stack}") | |
# otherwise, keep adding to the stack | |
else: | |
stack.append(int(n)) | |
print(f"stack: {stack}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment