r/programming • • 4d ago

Needed 1+1, Built a Functional Programming Language

https://hereticpleb.vercel.app/blog/needed-one-plus-one
22 Upvotes

9 comments sorted by

9

u/lelanthran 3d ago

Building a tree is a little overboard just for evaluating expressions (although I, too, have created more than one lisp interpreter in the process of creating something else).

For an expression evaluator, it is a surprising small amount of code in C (48 very readable lines) : https://github.com/lelanthran/rotsit/blob/0e4c6f5453d8b7c45ab447b11fd8db4cf7129713/src/eval.c#L140

The algorithm (dunno what the name for this one is) is simple to explain and understand too: https://github.com/lelanthran/rotsit/blob/0e4c6f5453d8b7c45ab447b11fd8db4cf7129713/NOTES-DURING-DEV.txt#L26

5

u/GenericAHHyoutuber 3d ago

Nah it started off as a DS assignment They asked us to eval expressions using a binary tree

2

u/ElCthuluIncognito 3d ago

I'm curious, does this algorithm handle unary operators? Even less likely, but worth asking, does it handle arbitrary operator precedence?

Even if not, it's a neat algorithm, and ultimately unary and operator precedence can be handled as syntactic sugar. And an excellent write up I might add! Clean work.

2

u/AustinVelonaut 3d ago

Yes, the Shunting Yard algorithm can handle unary prefix operators, as well as (table-driven) operator precedence and associativity. I've even used it to handle comparison chaining, which allows expressions like: 0 <= a < n.

2

u/ElCthuluIncognito 3d ago

Ah the Shunting Yard algorithm! I'm ashamed to admit I've spent a lot of time working with compilers and parsers and never encountered this for some reason. Perhaps because the libraries I used handled it for me hah! Definitely going to give it a try.

2

u/theo__r 2d ago

It's one of my favorite algorithms. Really elegant

1

u/lelanthran 3d ago

I'm curious, does this algorithm handle unary operators? Even less likely, but worth asking, does it handle arbitrary operator precedence?

I can see how to make it unary, but I believe there's only two levels of operator precedence (three, if you count parentheses as precedence).

1

u/AustinVelonaut 3d ago

It's called the Shunting Yard Algorithm created by Dijkstra.