The Science of Programming/SwayPresentations/Objects/Examples5
Appearance
Here's a switch using typical Sway syntax:
var x = 0; switch (x) { case(3) { println("greater"); } case(2) { println("equal"); } else { println("less"); } }
To implement switch, we start by defining the case function in anticipation of it being filtered.
function case(operand,$action,$) { list(operand,$action,$); }
Remember, a filter takes each statement in turn, so as we saw with filtering pop, one line functions are the best to filter.
The strategy for switch:
- create a filter with the switch expression in scope
- have the filter throw a success exception
- attach the filter to case
- run the body of the switch, looking for success
function switch(expr,$actions) { var result; function caseFilter(spec) { var val; if (expr == spec[0]) { throw(:success,force(spec[1])); } else if (spec[2] != :null) { throw(:success,force(spec[2][0])); } } case . filter = caseFilter; result = catch(force($actions)); if (error?(result)) { if(result . type == :success,result . value,throw(result)); } else { :null; } }