ZPE 1.9.1 (Kelso, February 2021) added support for the match
construct. Whilst
it's syntax is similar to that of a function, match
is not a function.
The match
statement is a very powerful, high-performance statement designed to be used
much like an inline when-is
statement, allowing both a concise, easy to use syntax and a performant construct
for simple comparison inline.
$a = value(input("Please guess a number")) $y = match($a : 0 => "Incorrect" 1 => "Incorrect" 2 => "Incorrect" 3 => "Incorrect" 4 => "Correct" ) print($y)
Whilst this does demonstrate one such use case, it is also lacking efficiency, so an else statement can be placed it as such:
$a = value(input("Please guess a number")) $y = match($a : 10 => "Correct" else => "Incorrect" ) print($y)
Whilst the ZPE compiler does support multiple else
statements
within a match
statement, it is technically a waste of resources and the runtime
will only interpret the first statement it finds.
Syntactically, the else
statement can be anywhere within the
match
statement, but I believe it looks better at the end.
Writing a guess the number game is also very easy using the match construct:
$rand = random_number(0, 10) $res = "" while ($res != "Correct") $user_input = value(input("Please guess a number")) $res = match($user_input : $rand => "Correct" else => "Incorrect") end while print($res)
Syntactic sugar
The match
statement supports syntactic sugar in terms of
commas to make it easier to read:
$a = value(input("Please guess a number")) $y = match($a : 10 => "Correct", else => "Incorrect" ) print($y)
PHP style
Since version 1.9.5 (Melrose, May 2021), match statements can be written using identical syntax to PHP 8's syntax. This means they can use the curly brace syntax. This example uses this coding style.
The following example generates a random number between 0 and 500 and assigns it to
a variable. It doubles the value of the random number and stores that in a variable.
The program then iterates between 0 and 1000 and when the value of the
random number is it outputs "What I wanted"
.
The do_nothing
function here means that the print command will
not even print anything to the screen.
$rand = random_number(0, 500) $double = $rand * 2 for($x = 0 to 1000) print(match($x) { $rand => "What I wanted", $double => "Double what I wanted" else => do_nothing() }) end for