whens and lets
Do you know how a YS assignment actually works?
It compiles into a Lisp let
form.
Let's take a look...
Assignments are let bindings🔗
Here we compile a main
function that assigns 2 variables, x
and y
.
$ ys -ce '
defn main():
x =: 6
y =: 7
say: x * y
'
(defn main [] (let [x 6 y 7] (say (mul+ x y))))
(apply main ARGS)
This makes it fairly easy to understand how variables inside functions are scoped.
let
in when
🔗
Let's try to use let
and when
together:
$ NAME=Cammie ys -e '
defn main():
when ENV.NAME:
warn: "Hello, $(ENV.NAME)!"
'
Hello, Cammie!
This works, but we had to calculate ENV.NAME
twice.
We might not want to do that.
We can solve it with a let binding.
$ NAME=Sammie ys -e '
defn main():
name =: ENV.NAME
when name:
warn: "Hello, $name!"
'
Hello, Sammie!
This also works, but I don't like needing an assignment just to ask the question.
Introducing when-let
🔗
There's a when-let
function that does exactly what we want.
NAME=Tammie ys -e '
defn main():
when-let name ENV.NAME:
warn: "Hello, $name!"
'
Hello, Tammie!
Nice!
There's also an if-let
function, but it doesn't set the variable when the
condition is not true.
That's all I got for today.
Let's get into some more interesting stuff this weekend!