To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Official ZPE/YASS documentationMatch statements

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.

YASS
$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:

YASS
$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:

YASS
$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:

YASS
$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.

YASS
$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
  
Comments

There are no comments on this page.

New comment
Reply
Feedback 👍
Comments are sent via email to me.