In this post we are implementing the 'for' loop:
class Interpreter:
def __init__(self):
self.scope=[{}]
self.loop_stack=[]
# ...(previous code)...
# 'For' loop is not much different from 'while' loop
# for(inits; cond; increments) {block}
def For(self,xs):
self.loop_stack.append({"break":False,"continue":False})
_, inits, cond, increments, block = xs
for x in inits:
self.eval(x)
while self.eval(cond):
if isinstance(block[0],list):
for x in block:
self.eval(x)
if self.loop_stack[-1]["break"]:
self.loop_stack.pop()
return
if self.loop_stack[-1]["continue"]:
self.loop_stack[-1]["continue"]=False
break
else:
self.eval(block)
for x in increments:
self.eval(x)
self.loop_stack.pop()
code=[
["Set","sum",0],
["For", [["Set","i",0]],
["Lt", ["Get","i"], 100],
[["Set","i", ["Add",["Get","i"], 1] ]],
[
["Set","sum", ["Add",["Get", "sum"],["Get","i"]]],
["Print","i=",["Get","i"],", sum=",["Get","sum"]],
["If", ["Eq", ["Get", "i"], 10],
["Break"],[]
],
]],
]
interpreter=Interpreter()
interpreter.run(code)
Output:
i=0, sum=0
i=1, sum=1
i=2, sum=3
i=3, sum=6
i=4, sum=10
i=5, sum=15
i=6, sum=21
i=7, sum=28
i=8, sum=36
i=9, sum=45
i=10, sum=55
Link to complete code.
Top comments (0)