Fancier YS Conditionals
Most languages support a case
or switch
construct which is a way to handle
multiple conditions.
YS supports several similar but different constructs for this.
Today we'll focus on the cond
and case
functions.
Using cond
🔗
The cond
function takes an ordered set of pairs each consisting of a predicate
and an action.
Since we are writing code in YAML, it uses mappings for this.
Each pair has a predicate key and an action value.
# cond.ys
!YS-v0
each x [-1 2 30 400 5000 "sixty thousand"]:
kind =:
cond:
x:int?:not: "not a"
x < 0: "a negative"
x < 10: "a single digit"
x < 100: "a double digit"
x < 1000: "a triple digit"
else: "a huge"
say: "$x is $kind number"
Let's run it:
$ ys cond.ys
-1 is a negative number
2 is a single digit number
30 is a double digit number
400 is a triple digit number
5000 is a huge number
sixty thousand is not a number
The cond
function tries each predicate in order until one of them is true.
Then it applies the action of that predicate and it is finished.
Just in case
🔗
There's a similar function called case
.
This one takes a value and a set of things it might be equal to.
The set consists of a mapping whose pairs contain a value and an action.
The case
function also supports an else
pair, like cond
.
# case.ys
!YS-v0
each n (1 .. 4):
say:
case n:
1: "One for the money."
2: "Two for the show."
3: "Three to get ready."
else: "Now, go cat, go!"
And then:
$ ys case.ys
One for the money.
Two for the show.
Three to get ready.
Now, go cat, go!
Your YS wish is my command.
Gotta go!
See you tomorrow.