Conditional structures/J: Difference between revisions

Line 67:
===conditions without conditions===
 
Conditional effects can often be obtained without conditional structures. In J, a boolean result is a 1 or a 0, where 1 represents true and 0 represents false. If we have a boolean array <code>B</code> which corresponds in shape to a numeric argument <code>Y</code>, and we have a function <code>F</code> where we want the result of <code>F Y</code> where <code>B</code> is true, and instead want the original value of <code>Y</code> where B is false, we can use an expression like:
 
<lang J>(Y * -. B) + B * F Y</lang>
 
This also assumes, of course, that F is well behaved (that we can ignore any issues related to side effects), and has the right shape. [The token <code>-.</code> is J's boolean "not" verb. And the tokens <code>+</code> and <code>*</code> are J's addition and multiplication verbs.]
 
If you do not want to pay for the execution of <code>F Y</code> for cases where <code>B</code> is false, and if <code>Y</code> is a simple list, then a variation would be:
<lang J>(Y * -. B) + F&.(B&#) Y</lang>
6,962

edits