More Fancier YS Conditionals
Yesterday we looked at the cond
and case
functions.
The cond
function has a couple cousins: condp
and condf
.
Let's take a look at them.
Using condp
🔗
The p
in condp
stands for "predicate".
A predicate is a function that returns a boolean value.
The condp
function takes a predicate function, a value and a set of pairs.
The pairs consist of a value and an action.
The predicate function should take two arguments and perform some sort of comparison. The first argument comes from the pair's value and the second argument is the initial value.
Let's try it in yesterday's example.
# condp.ys
!YS-v0
each n (1 .. 4):
say:
condp eq n:
1: "One for the money."
2: "Two for the show."
3: "Three to get ready."
else: "Now, go cat, go!"
Here we use the eq
function to compare the pair value to the topic value.
Each pair is tried in order until one matches.
The else
pair is used if no match is found.
It seems to work as expected when we run it.
$ ys condp.ys
One for the money.
Two for the show.
Three to get ready.
Now, go cat, go!
Using condf
🔗
The f
in condf
stands for "function".
The condf
function takes a value and a set of pairs.
The pairs consist of a function and an action.
The value is passed the the pair function which should return a boolean value.
Each pair is tried in order until one matches.
The else
pair is used if no match is found.
Let's try it out.
$ ys -e '
each n [1 "two" 3.1415 true nil {}]:
say:
condf n:
nil?: "Value is nil."
true?: "Value is true."
int?: "$n is an integer."
float?: "$n is a float."
string?: "$n is a string."
else: "Value is something else."
'
1 is an integer.
two is a string.
3.1415 is a float.
Value is true.
Value is nil.
Value is something else.
Recap🔗
if
takes a condition, a then clause, and an else clause.when
takes a condition and a then block.cond
tries a set of cond/action pairs, tested in order.case
takes a value and tries a set of value/action pairs called in parallel.condp
takes a predicate function, a value, and a set of comparator/action pairs, tested in order.condf
takes a value, and a set of function/action pairs. The functions are called with the value and tested in order.
YS has a lot of different ways to handle conditionals.
Tomorrow we'll take a look at one more, the when-let
function.