Comparison and Selection Functions

Prev Next

Introduction

Common programming languages use standard constructs like if ... else or condensed statements such as [condition] ? [expression if true] ? [expression if false], Aiming to allow for more dense and efficient coding, B4P provides a set of effective comparison and selection functions. The functions come in two fragrances:

select ... ()

In these functions all parameters are fully calculated regardless of the condition and/or if the values are finally selected or discarded. This approach is most efficient if the values are constants or simple expression (e.g. a constant, referring to variable, a table entry, a simple calculation, etc.) or if manipulations must be made in any case, e.g. doing a function call or incrementing/decrementing variables.

Program example - all expressions are calculated:
       a[] = select if( true, echo(yes), echo(no) ); // Note. Both 'yes' and 'no' are printed here
       echo("Result is ", a[] );
Result:
yes
no
Result is yes

Try it yourself: Open LIB_Features_Comparison_and_selection_functions.b4p in B4P_Examples.zip. Decompress before use.

pick ... ()

In these functions, the expressions for the values to select are only calculated if the results are needed. Otherwise, these expressions will be skipped. This approach saves a lot of computation effort if more sophisticated expressions are contained. In addition, if a variable in an expression not selected is not defined, this does not matter because that expression is skipped.

Program example - 'echo(no)' is not executed:
       a[] = pick if( true, echo(yes), echo(no) ); // Note: Only 'yes' if printed
       echo("Result is ", a[] );
Output
yes
Result is yes

Try it yourself: Open LIB_Features_Comparison_and_selection_functions_01.b4p in B4P_Examples.zip. Decompress before use.




Procedures and Functions Provided:


Select parameter based on numeric value in 1st parameter:
    pick
    select

Select parameter based on boolean value in 1st parameter:
    pick if
    select if

Select parameter based on multiple boolean values:
    pick ifs
    select ifs

Select value from variable if existing:
    pick if existing
    pick if existing and valid
    select if existing
    select if existing and valid

Select parameter based on matching corresponding values:
    pick by value
    select by value

Selection based sequence of comparisons:
    compare pick
    compare select

Replacing values and set elements:
    replace if