patch_seq_cond

Function patch_seq_cond 

Source
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_cond(stack: Stack) -> Stack
Expand description

Multi-way conditional combinator

§Stack Effect

( value [pred1] [body1] ... [predN] [bodyN] N -- result )

§How It Works

  1. Takes a value and N predicate/body quotation pairs from the stack
  2. Tries each predicate in order (first pair = first tried)
  3. When a predicate returns true, executes its body and returns
  4. Panics if no predicate matches (always include a default case)

§Quotation Contracts

  • Predicate: ( value -- value Bool ) - keeps value on stack, pushes true or false
  • Body: ( value -- result ) - consumes value, produces result

§Default Case Pattern

Use [ true ] as the last predicate to create an “otherwise” case that always matches:

[ true ] [ drop "default result" ]

§Example: Classify a Number

: classify ( Int -- String )
  [ dup 0 i.< ]  [ drop "negative" ]
  [ dup 0 i.= ]  [ drop "zero" ]
  [ true ]       [ drop "positive" ]
  3 cond
;

-5 classify   # "negative"
0 classify    # "zero"
42 classify   # "positive"

§Example: FizzBuzz Logic

: fizzbuzz ( Int -- String )
  [ dup 15 i.% 0 i.= ]  [ drop "FizzBuzz" ]
  [ dup 3 i.% 0 i.= ]   [ drop "Fizz" ]
  [ dup 5 i.% 0 i.= ]   [ drop "Buzz" ]
  [ true ]              [ int->string ]
  4 cond
;

§Safety

  • Stack must have at least (2*N + 1) values (value + N pairs)
  • All predicate/body values must be Quotations
  • Predicates must return Bool