if - You Are Special
Yesterday I told you that if
is a function.
I lied.
In reality, if
is a "special form".
I'll explain special forms in a minute, but let's just say that they're "special"!
Functions calls evaluate their arguments
Consider this code:
$ ys -e '
x =:
DBG:
add:
sqr(4):DBG
sqr(5):DBG
say: x
'
>>>16<<<
>>>25<<<
>>>41<<<
41
DBG
is a function that prints its arguments and then returns the value of the
last one.
We can see clearly that sqr(4)
and sqr(5)
are evaluated first, and then
add
is called with the results.
Let's try the same thing with if
:
$ ys -e '
x =:
DBG:
if (rand(2):DBG > 1):DBG:
sqr(4):DBG
sqr(5):DBG
say: x
'
>>>1.288428806185308<<<
>>>true<<<
>>>16<<<
>>>16<<<
16
It looks like sqr(5)
was never evaluated.
That's exactly how you want an if
expression to work.
An if
expression is a function that takes three arguments:
- A "condition clause"
- A "then clause"
- An "else clause"
Based on the truthiness of the condition clause, only one of the other two clauses is evaluated.
This is true in practically any programming language.
About Special Forms
Most Lisp languages have special forms.
Special forms "look" like functions in that they use parentheses containing the form name and any arguments. But they are built into the language to behave differently.
YS has about a dozen special forms, and we've already been using them in this
series.
For example x =: y
compiles into a Lisp def
or let
form (depending on
the context) which are both special forms.
Fuggedaboudif
!
Now that you know about special forms, you can forget about them.
In YS, everything's a function. A few of them are special. They all try to do the right thing.
Enjoy the rest of your weekend!