Conditionals

“if it has no special forms, how does it have if”

Revisit Do again

On the previous page we looked at the do function. It accepts one argument, a block of code and evaluates it.

do { print "Hello" }
; prints: Hello

If

Now think of a function similar to do function. But it takes additional argument and only evaluates the block of code if the first argument is True (1).

And so we get if, and it’s just an ordinary builtin function, just like do is.

if 0 { print "Moon" }
; doesn't print anything

if 1 { print "Sun!" }
; prints: Sun!

if 10 < 20 { print "Hello" }
; prints: Hello

value: 101

if is-integer value { print "Great!" }
; prints: Great!

Either

To achieve if-else behaviour we have another function called either.

It accepts conditional and two blocks. If condition is true it evaluates first block, if not the second.

either 1 { print "hello" } { print "yello" }
; prints: hello

either 0 { print "hello" } { print "yello" }
; prints: yello

Like everything else in Rye either is an expression and returns something. It returns the last value in the block it evaluates. So it acts as a ternary operator would in C-like languages.

print either 1 { "hello" } { "yello" }
; prints: hello

num: 99
increment: true              ; true is just a function that returns 1
print num + either increment { inc num } { num }
; prints: 199

Switch

Switch is also a function in Rye. Similar to either it returns the last value of evaluation.

switch 2 { 1 { print "one" } 2 { print "two" } }
; prints: two

animal: "duck"

print switch animal { "duck" { "quack" } "dog" { "woof" } }
; prints: quack

Code blocks are still blocks

Blocks of code are just like other Rye blocks, we can store them in a variable for example. There is nothing special about if, it’s just a function.

say-hello: { print "hello" }

if 20 > 10 say-hello