Bite sized posts are continuing. In this post we are implementing If keyword:
class Interpreter:
    # ... previous code ...
    def If(self,xs):
        _, cond, trueblock, falseblock = xs
        if self.eval(cond):
            if isinstance(trueblock[0],list):
                for x in trueblock:
                    self.eval(x)
            else:
                self.eval(trueblock)
        else:
            if falseblock:
                if isinstance(falseblock[0],list):
                    for x in falseblock:
                        self.eval(x)
                else:
                    self.eval(falseblock)
code=[
    ["If",True,
       # True block, 3 statements
       [["Print","answer is 42"],
        ["Print","that is 21*2"],
        ["Print","that is just an ordinary number"]],
       # False block
       ["Print","answer is something else"]   
    ],
    ["Print",["Mul","-",42]],
    ["If",False,
       ["Print","answer is 42"],
       ["Print","answer is something else"]   
    ]   
]
interpreter=Interpreter()
interpreter.run(code)
Output:
answer is 42
that is 21*2
that is just an ordinary number
------------------------------------------
answer is something else
    
Top comments (0)