Conditional Functions
By defining our fun
function we’ve already shown how powerful our language is in its ability to define functions that look like new syntax. Another example of this is found in emulating the C switch
and case
statements. In C these are built into the language, but for our language we can define them as part of a library.
We can define a function select
that takes in zero or more two-element lists as input. For each two element list in the arguments it first evaluates the first element of the pair. If this is true then it evaluates and returns the second item, otherwise it performs the same thing again on the rest of the list.
(fun {select & cs} {
if (== cs nil)
{error "No Selection Found"}
{if (fst (fst cs)) {snd (fst cs)} {unpack select (tail cs)}}
})
We can also define a function otherwise
to always evaluate to true
. This works a little bit like the default
keyword in C.
; Default Case
(def {otherwise} true)
; Print Day of Month suffix
(fun {month-day-suffix i} {
select
{(== i 0) "st"}
{(== i 1) "nd"}
{(== i 3) "rd"}
{otherwise "th"}
})
This is actually more powerful than the C switch
statement. In C rather than passing in conditions the input value is compared only for equality with a number of constant candidates. We can also define this function in our Lisp, where we compare a value to a number of candidates. In this function we take some value x
followed by zero or more two-element lists again. If the first element in the two-element list is equal to x
, the second element is evaluated, otherwise the process continues down the list.
(fun {case x & cs} {
if (== cs nil)
{error "No Case Found"}
{if (== x (fst (fst cs))) {snd (fst cs)} {
unpack case (join (list x) (tail cs))}}
})
The syntax for this function becomes really nice and simple. Try to see if you can think up any other control structures or useful functions that you’d like to implement using these sorts of methods.
(fun {day-name x} {
case x
{0 "Monday"}
{1 "Tuesday"}
{2 "Wednesday"}
{3 "Thursday"}
{4 "Friday"}
{5 "Saturday"}
{6 "Sunday"}
})