DEV Community

sma
sma

Posted on • Edited on

2 1

Lets build a simple interpreter from scratch in python, pt.04: Comparison functions

In this post we are adding comparison functions to our interpreter:

class Interpreter:

    # .... previous code ....

    def Lt(self,xs):
        return self.eval(xs[1]) < self.eval(xs[2])
    def Gt(self,xs):
        return self.eval(xs[1]) > self.eval(xs[2])
    def Lte(self,xs):
        return not self.Gt(xs)
    def Gte(self,xs):
        return not self.Lt(xs)
    def Eq(self,xs):
        return self.eval(xs[1]) == self.eval(xs[2])
    def NotEq(self,xs):
        return not self.Eq(xs)

code=[

    ["If",["Lte",3,5],
       ["Print","3 <= 5"],
       ["Print","3 > 5"]   
    ],

    ["If",["NotEq",3,5],
       ["Print","3 != 5"],
       ["Print","3 == 5"]   
    ]   
]

interpreter=Interpreter()

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

Output:

3 <= 5
3 != 5
Enter fullscreen mode Exit fullscreen mode

Part 5: Variables

Image of PulumiUP 2025

From Cloud to Platforms: What Top Engineers Are Doing Differently

Hear insights from industry leaders about the current state and future of cloud and IaC, platform engineering, and security.

Save Your Spot

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay