A deep dive into converting a simple arithmetic expression into a binary tree, leading to a custom language in C.
64 comments
> Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
More precisely, I had figured out how to parse an Excel formula (keeping track of braces and commas, I recall!). For the actual math symbols, all I had to do was rewrite them as Excel formulas!
3+6*2 -> 3+MUL(6,2) -> ADD(3,MUL(6,2))
In order of precedence. And then just evaluate the resulting formulas inside-out:
ADD(3,MUL(6,2)) -> ADD(3,12) -> 15
It somehow ended up being a thousand lines of code. Another guy doing the same assignment told me he did it in 50 with regular expressions.
In retrospect, what I did reminds me of hammering in a nail with a screwdriver.
I ended up revisiting the idea later (just the math parser, no ADD() syntax) and it was much nicer, like 30 lines of JS (no regex either!). (Well, you can do it in one line with eval, but yea :)
I did the same for my performant implementation of pure functional programming language BLC/BLC2, which in 400+ lines contains a graph reduction engine for combinatory logic, to which the lambda calculus programs are converted by Kiselyov's bracket abstraction algorithm.
Used to be a common refrain when we were whiteboarding new features. Usually as a check on somebody's overly ambitious thinking.
I counted 23 "just"s in the article. Bravo. Sometimes you have to _just_ plow ahead.
Read the full thread on Hacker News →
Related stories
- Flix - The Elegance of Functional Programming with the Conciseness of Logic Programmingflix.github.ioLobsters · 11 points · about 10 years ago
- Why Functional Programming Matters by John Hughes [1984]cse.chalmers.seLobsters · 10 points · about 10 years ago
- FP^2: Fully in-Place Functional Programmingmicrosoft.comLobsters · 32 points · over 3 years ago
- Lobsters · 10 points · 6 months ago
- Make the Raku programming language familiar to C++ programmerssoftware.gellyfish.co.ukLobsters · 8 points · over 4 years ago
- Hacker News · 11 points · 8 days ago