﻿ ApplyIf – Algosim documentation
Algosim documentation: ApplyIf

ApplyIf

Conditionally applies a function to every element in a container.

Syntax

• `ApplyIf(X, p, f[, n])`

• `X` is a container that is not a set

• `p` is a predicate

• `f` is a function

• `n` is a positive integer

Description

If `X` is any container except a set, `p` a boolean-valued function defined on `X`, and `f` a function defined on `X`, then `ApplyIf(X, p, f)` returns a copy of `X` in which every element `x` for which `p(x)` is `true` has been replaced by `f(x)`.

ApplyIf(X, p, f, n) instead tests and transforms element on level `n` in `X`, with `n = 1` being `X` itself.

Examples

`A ≔ RandomIntMatrix(10, 0, 10)`
```⎛9  4  9  1  1  9  3  1  7  1⎞
⎜3  2  8  2  1  4  4  3  9  2⎟
⎜5  7  5  0  3  0  4  4  0  3⎟
⎜8  5  1  4  4  7  2  3  9  7⎟
⎜5  9  0  4  8  5  3  6  3  5⎟
⎜1  6  3  6  1  2  4  9  3  4⎟
⎜2  5  6  7  9  1  4  0  4  4⎟
⎜6  5  6  1  1  7  6  6  3  5⎟
⎜6  1  1  4  5  7  6  0  1  8⎟
⎝2  0  4  1  4  3  4  4  4  4⎠
```
`ApplyIf(A, IsNonZero, x ↦ ⌊9/x⌋)`
```⎛1  2  1  9  9  1  3  9  1  9⎞
⎜3  4  1  4  9  2  2  3  1  4⎟
⎜1  1  1  0  3  0  2  2  0  3⎟
⎜1  1  9  2  2  1  4  3  1  1⎟
⎜1  1  0  2  1  1  3  1  3  1⎟
⎜9  1  3  1  9  4  2  1  3  2⎟
⎜4  1  1  1  1  9  2  0  2  2⎟
⎜1  1  1  9  9  1  1  1  3  1⎟
⎜1  9  9  2  1  1  1  0  9  1⎟
⎝4  0  2  9  2  3  2  2  2  2⎠
```