case ( obj assoc -- )
Factor documentation > Factor handbook > The language > Combinators > Conditional combinators
Prev:cond ( assoc -- )
Next:Expressing conditionals with boolean logic


Vocabulary
combinators

Inputs and outputs
objan object
assoca sequence of object/word,quotation pairs, with an optional quotation at the end


Word description
Compares obj against the first element of every pair, first evaluating the first element if it is a word. If some pair matches, removes obj from the stack and calls the second element of that pair, which must be a quotation.

If there is no case matching obj, the default case is taken. If the last element of cases is a quotation, the quotation is called with obj on the stack. Otherwise, a no-cond error is rasied.

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

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


Examples
SYMBOL: yes SYMBOL: no SYMBOL: maybe maybe { { yes [ ] } ! Do nothing { no [ "No way!" throw ] } { maybe [ "Make up your mind!" print ] } [ "Invalid input; try again." print ] } case


Definition
USING: arrays kernel quotations sequences ;

IN: combinators

: case ( obj assoc -- )
case-find {
{ [ dup array? ] [ nip second call ] }
{ [ dup callable? ] [ call ] }
{ [ dup not ] [ drop no-case ] }
} cond ;