if - We Must
Yesterday we talked about if
being a special form.
It turns out that if
is special in other ways.
For instance, it requires both the then
and else
clauses to be present…
but… it doesn't require the actual then
and else
keywords.
Today we'll finish our conversation about if
and go over all the specifics.
The Lisp Point of View🔗
In the Lisp code that YS compiles to, the form looks like this:
(if <condition> <then> <else>)
.
Note
Lisp allows you to skip the <else>
clause, in which case it defaults to
nil
.
But it also discourages this, and encourages you to use the when
function
instead.
We'll talk about when
in a future post.
YS does not allow you to skip the <else>
clause.
If you don't have one, use nil
or switch to when
.
In YS we can write that in many ways:
x =:
if a: b c
x =:
if a:
=>: b
=>: c
x =: if(a b c)
x =: a.if(b c)
This works fine when the <then>
and <else>
clauses are a single form (both
in Clojure and YS).
If a clause needs more than one form you need to combine them into a single
form.
In Clojure you do this with a do
form, and you can do that in YS too.
The do
form is a special form that evaluates all its arguments and returns the
value of the last one.
x =:
if a:
do:
b: 1
b: 2
do:
c: 1
c: 2
YS makes this prettier by allowing you to use the words then
and else
instead of do
or =>:
.
$ ys -ce '
x =:
if a:
then:
b: 1
b: 2
else:
c: 1
c: 2
'
(def x (if a (do (b 1) (b 2)) (do (c 1) (c 2))))
The Fine Print🔗
In YS you can use else
without using a then
first, but if you use then
you must use else
too.
You'll get an error if you don't.
YS just reads better this way.
$ ys -ce '
x =:
if a:
b: 1
else:
c: 1
c: 2
'
(def x (if a (b 1) (do (c 1) (c 2))))
$ ys -ce '
x =:
if a:
then:
b: 1
b: 2
c: 1
'
Compile error: Form after 'then' must be 'else'
Now you know all about if
.
There are several other cool conditional functions in YS.
We'll get there!