11.5.3 Branching with select
In certain situations, you are working with a particular two-argument predicate (such as == or <). The value of the first argument to the predicate will always be the same, and you would like to perform different actions based on the second value. You can use both if and case to handle this situation, but the select control structure is more concise. The following example interprets traffic-light colors:
define method color-action
(color :: <symbol>) => (action :: <symbol>)
select (color)
#"red" => #"stop";
#"yellow" => #"slow";
#"green" => #"go";
end select;
end method color-action;
The select control structure uses == for the default predicate. For example, in the preceding select statement, the symbol #"stop" will be returned if color == #"red". If you require a different predicate, use the by clause, as shown in the following example, which interprets age from a number representing years:
define method interpret-age
(age :: <nonnegative-integer>) => (description :: <string>)
select (age by \<)
13 => "youngster";
20 => "teenager";
60 => "adult";
otherwise => "senior";
end select;
end method interpret-age;
The preceding method returns the string "youngster" when provided an age less then 13; returns "teenager" when the age is between 13 and 20; and returns "adult" when the age is between 20 and 60. In all other cases, it returns "senior".




