Conditional structures/J: Difference between revisions

Content added Content deleted
Line 67: Line 67:
===conditions without conditions===
===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 B which corresponds in shape to a numeric argument Y, and we have a function F where we want F Y where B is true, and Y where B is false, we can use an expression like:
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>
<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 -. is J's boolean "not" verb.]
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 F Y for cases where B is false, and if Y is a simple list, then a variation would be:
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>
<lang J>(Y * -. B) + F&.(B&#) Y</lang>