1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
*View this file with results and syntax highlighting [here](https://mlochbaum.github.io/BQN/doc/choose.html).*
# Choose
The 2-modifier Choose (`βΆ`) applies one function from a list `π`, based on the selecting index returned by a function `π½`. It's a combinator form of [Pick](pick.md) (`β`), so that `{fβ(π¨π½π©)βπ β π¨Fπ©}` is a complete definition. For example, the function below subtracts 1 from its argument if negative and adds 1 if positive.
0βΈβ€βΆβ¨-β1, +β1β©Β¨ 3βΏΒ―1βΏ5
Here the selection function `π½` is `0βΈβ€`, while `π` is a list of two functions `β¨-β1, +β1β©`. On the first argument, `3`, `π½3` is `0β€3`, or `1`, so the function `+β1` from `π` is chosen. The use of array indices means "false" comes first in `π` and "true" comes second, which is backwards relative to if-else constructs in most programming languages (including BQN's own [predicates](block.md#predicates)). When using a comparison for `π½` I strongly prefer to phrase it as `nβΈ<` or `nβΈβ€` so that smaller values go through the first one and larger functions go through the second. This doesn't apply so much when comparing two arguments since one is smaller but the other's larger, so I don't have an easy answer for that.
2 >βΆβ£βΏβ’ 6 # A minimum function (β)
The advantage of using an index is that Choose works with any number of options.
Fn β (β"rtd"ββ)βΆβ¨β½, 1βΈβ, 1βΈβ, β’β© # Reverse, take 1, drop 1
Fn "r123"
Fn "d123"
Fn "123" # Default
The selection function in `Fn` uses [Index of](search.md#index-of) (`β`) to find the index of the first character in the list `"rtd"`. An extra value in `π` serves as a default function if it's none of those, since the result of `π½` is `3` in that case. A similar function that's often useful is [Bins](order.md#bins), for grouping inputs into intervals rather than by exact matching.
Choose is necessary for [tacit](tacit.md) programming, but tacit programming is not necessary to be an effective BQN programmer! Consider using block features like [predicates](block.md#predicates) when Choose isn't working with your program's flow.
Because Choose is based on [Pick](pick.md), it retains the features of negative, multidimensional, and multiple selection. Negative indexing might make sense if there's some special `Β―1` value, and if the options naturally form an array, multidimensional indexing is pretty neat. Selecting multiple values from `π`, which happens if the result of `π½` is an array of arrays, is never useful because the array result from `π½` acts as a constant function. It's much clearer to express it as `π½βπΛ`.
|