DEV Community

sma
sma

Posted on • Edited on

1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay