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

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

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay