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 (โ
), 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 โจ 4 ยฏ2 6 โฉ
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). 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 (โ) 2
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" "321r" Fn "d123" "123" Fn "123" # Default "123"
The selection function in Fn
uses 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, for grouping inputs into intervals rather than by exact matching.
Choose is necessary for tacit programming, but tacit programming is not necessary to be an effective BQN programmer! Consider using block features like predicates when Choose isn't working with your program's flow.
Because Choose is based on Pick, 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 ๐ฝโ๐ห
.