Tutorial 2 of 4

Build a calculator

A small command-line calculator that reads a sum like 4 + 5, evaluates it, and loops until you type quit.

Step 1: The four operations

Start with one function per operation - nothing new here beyond Functions:

func add = define(a, b) { return a + b; }
func subtract = define(a, b) { return a - b; }
func multiply = define(a, b) { return a * b; }
func divide = define(a, b) { return a / b; }

Step 2: Pick an operation by name

Falx has no switch statement, so an if/elseif chain comparing strings is the idiomatic way to dispatch on an operator symbol:

func calculate = define(a, op, b) {
    if (op == "+") { return add(a, b); }
    elseif (op == "-") { return subtract(a, b); }
    elseif (op == "*") { return multiply(a, b); }
    elseif (op == "/") { return divide(a, b); }
    else {
        output("Unknown operator: " + op);
        return null;
    }
}

Remember from Truthiness that op == "+" produces a real boolean, so it's always safe as an if condition - unlike handing op itself to if.

Step 3: Read a line, split it, run it

request(prompt) (see the built-ins reference) prints a prompt and reads one line of text. "4 + 5" splits on a space into three pieces, and .toReal() (see Strings) turns the numeric pieces into actual numbers:

let running = true;
while (running) {
    let line = request("Enter a sum like '4 + 5', or 'quit': ");
    if (line == "quit") {
        running = false;
        continue;
    }
    let parts = line.split(" ");
    let a = parts[0].toReal();
    let op = parts[1];
    let b = parts[2].toReal();
    output(a + " " + op + " " + b + " = " + calculate(a, op, b));
}
output("Goodbye!");

A sample run (what you type is after each prompt):

$ python -m src.Main run calculator.flx
Enter a sum like '4 + 5', or 'quit': 4 + 5
4.0 + 5.0 = 9.0
Enter a sum like '4 + 5', or 'quit': 10 / 4
10.0 / 4.0 = 2.5
Enter a sum like '4 + 5', or 'quit': quit
Goodbye!
Notice every number prints as 4.0, not 4 - .toReal() always produces a float, even for whole numbers. Use .toInt() instead if you specifically want integers and don't need decimals.

Try it yourself

  • Add a % (modulo) case to calculate().
  • Use an array to keep a running history of every calculation, and print it when the user types history.
  • Try dividing by 0 to see Falx's built-in cannot divide by zero runtime error, then wrap the "/" case in calculate() with a check of your own so the calculator prints a friendlier message instead of letting the program crash.