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.

  1. (fun {select & cs} {
  2. if (== cs nil)
  3. {error "No Selection Found"}
  4. {if (fst (fst cs)) {snd (fst cs)} {unpack select (tail cs)}}
  5. })

We can also define a function otherwise to always evaluate to true. This works a little bit like the default keyword in C.

  1. ; Default Case
  2. (def {otherwise} true)
  3. ; Print Day of Month suffix
  4. (fun {month-day-suffix i} {
  5. select
  6. {(== i 0) "st"}
  7. {(== i 1) "nd"}
  8. {(== i 3) "rd"}
  9. {otherwise "th"}
  10. })

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.

  1. (fun {case x & cs} {
  2. if (== cs nil)
  3. {error "No Case Found"}
  4. {if (== x (fst (fst cs))) {snd (fst cs)} {
  5. unpack case (join (list x) (tail cs))}}
  6. })

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.

  1. (fun {day-name x} {
  2. case x
  3. {0 "Monday"}
  4. {1 "Tuesday"}
  5. {2 "Wednesday"}
  6. {3 "Thursday"}
  7. {4 "Friday"}
  8. {5 "Saturday"}
  9. {6 "Sunday"}
  10. })