Conditionals

beginner

So far, your evaluator can compute with numbers, name values, and define functions. But it always does the same thing — there’s no way for it to choose.

Conditionals change that. With an if expression, the evaluator can look at a condition and decide which path to take.


Comparisons

Before the evaluator can make decisions, it needs a way to ask questions. Expressions like [5, ">", 3] ask “is 5 greater than 3?” and produce a booleantrue or false.

These are the building blocks of decisions.


The If Expression

Once you have booleans, you can use them to choose between two outcomes:

["if", [5, ">", 3], 10, 20]

This means: “if 5 is greater than 3, the result is 10, otherwise 20.”

The evaluator handles this in three steps:

  1. Evaluate the condition
  2. If the result is true, evaluate the consequent (the second expression)
  3. If the result is false, evaluate the alternative (the third expression)

NOTE

Only one branch is evaluated — not both. This matters when expressions have side effects, and it’s how real languages work too.


What You’ll Do

You’ll extend your evaluator with:

  • Comparison operators: <, >, ==, !=
  • An if expression that picks a branch based on a condition

Let’s start by teaching the evaluator to compare.

Steps