if - You Have to Ask!
Today we're going to look at the if
command.
In a functional language, if
statements are a bit different.
They'll, well, um... Functions.
So what's the big deal?
Functions have their own scope🔗
So if if
is a function then you can't use it to set state outside of its
scope.
Let me show you what I mean.
Consider this normal Python code:
$ python -c '
x = 500
if x > 100:
size = "big"
else:
size = "small"
print(size)
'
big
This will set size
to "big"
and then print it.
Let's try the same thing in YS:
$ ys -e '
x =: 500
if x > 100:
size =: "big"
size =: "small"
say: size
'
Error: Could not resolve symbol: size
Since if
is a function, size is a local variable inside it's scope.
Well that's a bummer.
How are we supposed to get simple stuff done with YS?
It's simple once you've seen it:
$ ys -e '
x =: 500
size =:
if x > 100:
then: "big"
else: "small"
say: size
'
big
We just need to make if
return what we want and then assign it to a variable
in the scope that we want it in.
But why then
and else
?🔗
We didn't have them in the first example. Why did we need them in the second example?
Well actually we didn't need them.
But if I'm honest, right now I'm out in the woods (with wifi!) with friends who would rather have me hanging out doing Summer stuff than telling you about YS.
So we'll save that for later...
Maybe tomorrow!