Defining functions with boolean tests

### 4.1.3 Defining functions with boolean tests

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

- ifte takes three arguments:
  - condition, a boolean condition.
  - restrue, the result to return if condition is true.
  - resfalse, the result to return if condition is false.
- ifte(condition,restrue,resfalse) returns restrue if condition holds and resfalse otherwise.

#### Example

You can define your own absolute value function with:

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

Hence:

myabs(-4)

4 |  |  |  |  |  |  |  |  |  |

However, myabs will return an error if it cannot evaluate the condition.

myabs(x)

Ifte: Unable to check test Error: Bad Argument Value |  |  |  |  |  |  |  |  |  |

The ?: construct behaves similarly to ifte, but is structured differently and does not return an error if the condition cannot be evaluated.

- The ?: construct takes three arguments:
  - condition, a boolean condition.
  - restrue, the result to return if condition is true.
  - resfalse, the result to return if condition is false.
- condition? restrue: resfalse returns restrue if condition holds and resfalse otherwise.

#### Example

You can define your absolute value function with

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

If you enter

myabs(-4)

you will again get

4 |  |  |  |  |  |  |  |  |  |

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

myabs(x)

x≥ 0 ? x : −x |  |  |  |  |  |  |  |  |  |

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

- when (and IFTE) take three arguments:
  - condition, a boolean condition.
  - restrue, the result to return if condition is true.
  - resfalse, the result to return if condition is false.
- when(condition,restrue,resfalse) and IFTE(condition,restrue,resfalse) both return restrue if condition holds and resfalse otherwise.

(condition) ? restrue : resfalse
when(condition,restrue,resfalse)

and

IFTE(condition,restrue,resfalse)

all represent the same expression.

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

- piecewise takes an odd number of arguments:
  - cond1, return1, cond2, return2, …, condn, returnn, an arbitrary number of pairs of conditions and corresponding return values.
  - default, a result to return if none of the conditions are true.
- piecewise(cond1,return1,…,condn,returnn,default) returns returnk if condk is the first true condition, or default if none of the conditions are true.

#### Example

To define

f(x)= |
⎧ ⎪ ⎨ ⎪ ⎩ |
−2 | if x < −2
3x+4 | if −2 ≤ x < −1
1 | if −1 ≤ x < 0
x+1 | if x ≥ 0

enter:

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

To verify, plot f(x) for e.g. −3≤ x≤ 1.