PHP: A running calculator

Store small functions in an array and call them by name: a calculator that remembers its value.

What to build

A program that runs a list of calculator commands.

Requirements

  • The calculator starts at 0. Read lines until the input ends. Skip blank lines.
  • add N, sub N and mul N change the value. reset sets it to 0. show prints value = V.
  • Any other command prints unknown: WORD where WORD is the first word of the line.

Input

Any number of command lines.

Output

One line for every show and for every unknown command.

Constraints

At most 100 lines; the value always stays between -1000000 and 1000000.

Example

Input:

add 5
mul 3
show
sub 2
show

Output:

value = 15
value = 13

Why it works

A closure stored under each command name makes the program a table lookup instead of a long if chain.

Examples

Example 1 · Input
add 5
mul 3
show
sub 2
show
Expected output
value = 15
value = 13
Example 2 · Input
show
Expected output
value = 0

Hints

Hint 1

Keep the operations in an array: ["add" => fn($a, $b) => $a + $b, ...].

Hint 2

Look up the command with isset($ops[$cmd]) and update the running value.

Solution

Show one correct solution (try it yourself first)
<?php
$ops = [
    "add" => fn($a, $b) => $a + $b,
    "sub" => fn($a, $b) => $a - $b,
    "mul" => fn($a, $b) => $a * $b,
];
$value = 0;
while (($line = fgets(STDIN)) !== false) {
    $line = trim($line);
    if ($line === "") {
        continue;
    }
    $parts = explode(" ", $line);
    $cmd = $parts[0];
    if (isset($ops[$cmd])) {
        $value = $ops[$cmd]($value, (int) ($parts[1] ?? 0));
    } elseif ($cmd === "reset") {
        $value = 0;
    } elseif ($cmd === "show") {
        echo "value = $value\n";
    } else {
        echo "unknown: $cmd\n";
    }
}

▶ Open this solution in the compiler

Lesson: Scope and closures →