case ( obj assoc -- )
Factor handbook » The language » Combinators » Conditional combinators

Prev:cond ( assoc -- )
Next:Expressing conditionals with boolean logic


objan object
assoca sequence of object/quotation pairs, with an optional quotation at the end


Word description
Compares obj against the first element of every pair, evaluating the first element if it is a callable. If a pair matches, obj is removed from the stack and the second element of that pair (which must be a quotation ) is call ed.

If the last element of the assoc is a quotation, that quotation is the default case. The default case is called with the obj on the stack, if there is no other case matching obj.

If all the cases have failed and there is no default case to execute, a no-case error is raised.

The following two phrases are equivalent:
{ { X [ Y ] } { Z [ T ] } } case

dup X = [ drop Y ] [ dup Z = [ drop T ] [ no-case ] if ] if

no-case if the input matched none of the options and there was no trailing quotation.

USING: combinators io kernel ; IN: scratchpad SYMBOLS: yes no maybe ; maybe { { yes [ ] } ! Do nothing { no [ "No way!" throw ] } { maybe [ "Make up your mind!" print ] } [ drop "Invalid input; try again." print ] } case
Make up your mind!