10
4

6 回答 6

15

The trouble with these:

(f t)[x]
x⌷f t
x⊃f t

is that both t and f get evaluated.

If you want to short-circuit the thing, you can use guards:

{x:t ⋄ f}

This is equivalent to

if (x) {
    return t;
}
f;

in a C-like language.

于 2013-04-08T20:04:16.940 回答
10

Yes, there are APL programmers on SO (but not many!).

I think the answer is that there is no standard on this.

For a scalar solution, I use "pick":

  x⊃f t

While for a Boolean array I use indexing as you do above:

f t[x]

I always use index origin zero, so there is no need to add 1, and the parens are not needed.

If these are not simple enough, I think you have to cover them with a function named "if". That will also let you put the true and false in the perhaps more natural ordering of t f.

于 2013-04-02T15:31:01.363 回答
7
于 2015-09-06T17:30:40.787 回答
6

An old, old idiom which did something like C's ternary operator ? : and returned a result was the following:

  r←⍎(¯3 3)[x=42]↑'6×8 ⋄ 6×7' 

Note that this is written for origin 0 and the parens around the -3 3 are there for clarity.

x=42 evaluates to zero or one, depending on this answer we choose -3 or 3, and thus select and execute either the first 3 elements ("6x8") or last 3 elements ("6x7") of the string. The diamond ⋄ is just there for decoration.

Needless to say, one would probably not code this way if one had :if :else avaiable, though the control structure form would not return a result.

于 2013-10-30T12:51:52.047 回答
1
于 2015-09-23T04:44:55.500 回答
0

The APL expression:

(1+x=0)⌷y z 

should be the C language equivalent for

x?y:z

And all the others

(1+x>0)⌷y z 

for

x<=0?y:z

Etc. In general if a b c are expressions of respective languages the APL expression:

(1+~a)⌷b c

It should be equivalent to the C language:

a?b:c
于 2017-12-07T08:42:46.137 回答