In this post we are implementing the 'while' loop:
class Interpreter:
# ....(previous code)....
def While(self,xs):
_ , cond , block = xs
while self.eval(cond):
if isinstance(block[0],list):
for x in block:
self.eval(x)
else:
self.eval(block)
code=[
["Set","sum",0],
["Set","i",0],
["While", ["Lt", ["Get","i"], 100], [
["Set","i", ["Add",["Get","i"], 1] ],
["Set","sum", ["Add",["Get", "sum"],["Get","i"]]]
]],
["Print","sum(1..100) = ",["Get","sum"] ]
]
interpreter=Interpreter()
interpreter.run(code)
Output:
sum(1..100) = 5050
Top comments (0)