"match" expressions

Matching numbers

A match expression branches based on a single value. It can be any numeric type.

main void() log shape-name 3 log shape-name 4 log shape-name 11 shape-name string(sides nat) match sides as 3 "triangle" as 4 "square" else "{sides}-gon"

match is an expression and can be nested inside other expressions.

main void() a nat = 1 log match a as 1 "OK" else "what?"

Branches of the match can be squeezed onto one line using then.

main void() a nat = 1 log match a as 1 then "OK" else then "what?"

The argument to match can introduce a local.

main void() log match x = 3 as 2 then "two" as 4 then "four" else then "some other number: {x}"

About symbols

A symbol is a simple value that can tested against other symbol values using ==.
Like an enum value, this kind of value is intended to be used for its identity.
You can't directly access the characters in a symbol, although it can be converted to or from a string using to.

Think of the symbol type as an infinitely large enum supporting all possible values.
This makes it useful when you don't know all possible values up-front.

If you are dealing with a limited set of values with likely repetition, you should usually use a symbol.
For example, the keys of a json object are symbols.

Matching symbols and strings

match works on symbol and string values too.

String values may be unquoted (as in as left below) if they are valid Keen identifiers.
Otherwise they should be quoted like regular string literals.

main void() log opposite "left" log opposite "right" log opposite "potato" opposite symbol(a symbol) match a as left "right" as right "left" else "anti-{a}"

match also works on char8 or char32.

main void() log opposite "<" opposite char8(a char8) match a as l then "r" as r then "l" as "<" then ">" as ">" then "<" else then a

"else" branches

Unlike with an if expression, a match expression on a number or string-like type must have an else branch.
The reason is that match expressions are usually used with an enum or union, and in those cases no else is required.
This will be explained in Enums and flags and Unions.