DEV Community

sma
sma

Posted on • Updated on

Lets build a simple interpreter from scratch in python, pt.02 Basic Arithmetic

There are many great tutorials about this subject on the internet written by clever people. Maybe my post will not be as great as them or academic style like them but i will always try to keep it simple as possible as. KISS

In this post we are adding basic arithmetic to our interpreter.

class Interpreter:
    def __init__(self):
        pass

    def run(self,code):
        for xs in code:
            self.eval(xs)

    def eval(self,xs):
        if isinstance(xs,list):
            return self.__getattribute__(xs[0])(xs)
        return xs

    def Print(self,xs):
        if len(xs)==1:
            print()
            return
        l=len(xs)-1
        for i,x in enumerate(xs[1:]):
            e=self.eval(x)
            if i<l-1:
                print(e,end="")
            else:
                if e!=",":
                    print(e)
                else:
                    print(e,end="")

    # Basic arithmetic operations,
    # Notice how we call self.eval function recursively:

    def Add(self,xs):
        return self.eval(xs[1])+self.eval(xs[2])
    def Sub(self,xs):
        return self.eval(xs[1])-self.eval(xs[2])
    def Mul(self,xs):
        return self.eval(xs[1])*self.eval(xs[2])
    def Div(self,xs):
        return self.eval(xs[1])/self.eval(xs[2])

code=[

    ["Print","3 + 5 = ", ["Add", 3, 5]  ],

    ["Print","1 - 2 * 3 = ", ["Sub", 1, ["Mul", 2, 3] ] ],

    ["Print",["Add", "Hello ", "again "],"W",["Mul","o",10],"rld!"],

]

interpreter=Interpreter()

interpreter.run(code)
Enter fullscreen mode Exit fullscreen mode

Output:

3 + 5 = 8
1 - 2 * 3 = -5
Hello again Woooooooooorld!
Enter fullscreen mode Exit fullscreen mode

Part 3: If/Else

Top comments (0)