Pythonからの単純なインタプリタを構築します.06 : whileループ


この投稿では' while 'ループを実装します.
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)
出力:
sum(1..100) = 5050
完全なコードへのリンク:part6
リンク242479152