This is the third and final part of a series on building a simple calculator REPL in Rust. (You may with to read part one and part two first.)
Here we’re going to talk about the eval
function, which takes an array of tokens, and either returns the result of the calculation or an error. You may have noticed that I used Polish notation, e.g., + 3 4
in this language, with the expressions delimited by parentheses. The reason for this is two-fold: First, I want to make this into a more full-featured Lisp interpreter one day, and second, for the same reason that Lisp is written in prefix notation – it makes things easy to parse. As wikipedia says:
When Polish notation is used as a syntax for mathematical expressions by programming language interpreters, it is readily parsed into abstract syntax trees and can, in fact, define a one-to-one representation for the same. Because of this, Lisp (see below) and related programming languages define their entire syntax in terms of prefix notation (and others use postfix notation).
We can think of an expression like (* (+ 2 3) (+ 1 3))
as a tree, with the division operator at the root and (+ 2 3)
and (+ 1 3)
as sub-trees. One major difference in the language I’ve defined from Polish mathematical notation is that I allow an arbitrary number of operands to follow each operator, which is why I need parentheses. Continue reading “Calculator REPL Part 3: Evaluating the tokens”