Previous Up Next

6.1.3  Defining functions with boolean tests: ifte ?: when

You can use boolean tests to define functions not given by a single simple formula. Notably, you can use the ifte command or ?: operator to define piecewise-defined functions.


Example.
You can define your own absolute value function with:
Input:

myabs(x):= ifte(x >= 0, x, -1*x)

Afterwards, entering:
Input:

myabs(-4)

will return:

4

However, myabs will return an error if it can’t evaluate the condition.
Input:

myabs(x)

Output:

Ifte: Unable to check test Error: Bad Argument Value


The ?: construct behaves similarly to ifte, but is structured differently and doesn’t return an error if the condition can’t be evaluated.


Example.
You can define your absolute value function with

myabs(x):= (x >= 0)? x: -1*x

If you enter

myabs(-4)

you will again get

4

but now if the conditional can’t be evaluated, you won’t get an error.
Input:

myabs(x)

Output:

((x >= 0)? x: -x)


The when and IFTE commands are prefixed synonyms for the ?: construct.

(condition)? true-result: false-result
when(condition, true-result, false-result)

and

IFTE(condition, true-result, false-result)

all represent the same expression.

If you want to define a function with several pieces, it may be simpler to use the piecewise function.


Example.
To define

f(x) =




−2if  x < −2
3x+4if  −2 ≤ x < −1
1if  −1 ≤ x < 0
x + 1if  x ≥ 0

you can enter:
Input:

f(x):= piecewise(x < -2, -2, x < -1, 3*x+4, x < 0, 1, x + 1)

Previous Up Next