Conditional combinators - Factor Documentation (original) (raw)

The basic conditionals:
if ( ..a ? true: ( ..a -- ..b ) false: ( ..a -- ..b ) -- ..b )
when ( ..a ? true: ( ..a -- ..a ) -- ..a )
unless ( ..a ? false: ( ..a -- ..a ) -- ..a )

Forms abstracting a common stack shuffle pattern:

if* ( ..a ? true: ( ..a ? -- ..b ) false: ( ..a -- ..b ) -- ..b )

when* ( ..a ? true: ( ..a ? -- ..a ) -- ..a )
unless* ( ..a ? false: ( ..a -- ..a x ) -- ..a x )

Another form abstracting a common stack shuffle pattern:

?if ( ..a default cond: ( default -- new/f ) true: ( ..a new -- ..b ) false: ( ..a default -- ..b ) -- ..b )

?when ( ..a default cond: ( ..a default -- ..a new/f ) true: ( ..a new -- ..a x ) -- ..a default/x )
?unless ( ..a default cond: ( ..a default -- ..a new/f ) false: ( ..a default -- ..a x ) -- ..a default/x )

An if form with three quotations:

1if ( ..a x pred: ( ..a x quot: ( ..a x -- ..b ? ) -- ..b x ? ) true: ( ..b x -- ..c ) false: ( ..b x -- ..c ) -- ..c )

2if ( ..a x y pred: ( ..a x y -- ..b x y ? ) true: ( ..b x y -- ..c ) false: ( ..b x y -- ..c ) -- ..c )
3if ( ..a x y z pred: ( ..a x y z -- ..b x y z ? ) true: ( ..b x y z -- ..c ) false: ( ..b x y z -- ..c ) -- ..c )

Words that test or guard against conditions:

1check ( ..a x quot: ( ..a x -- ..b ? ) -- ..b x ? )

2check ( ..a x y quot: ( ..a x y -- ..b ? ) -- ..b x y ? )
3check ( ..a x y z quot: ( ..a x y z -- ..b ? ) -- ..b x y z ? )
1guard ( ..a x quot: ( ..a x -- ..b ? ) -- ..b x/f )
2guard ( ..a x y quot: ( ..a x y -- ..b ? ) -- ..b x/f y/f )
3guard ( ..a x y z quot: ( ..a x y z -- ..b ? ) -- ..b x/f y/f z/f )

Sometimes instead of branching, you just need to pick one of two values:

? ( ? true false -- true/false )

Two combinators which abstract out nested chains of if:

cond ( assoc -- )

case ( obj assoc -- )

Expressing conditionals with boolean logic

See also
Booleans, Bitwise arithmetic, both?, either?