If-Else conditions with APL?

2.6k views Asked by At

So, I'm wondering/asking; Is it possible to do an If-Statement in APL? If so how?

Here's my code

    'Please enter a number to count to: ' 
 number ←⎕ 
 ⍳number

How do I get an if-statement to where if the user inputs a number over 100 it will print out "too high" and end; or if it's 100 or under then it will just continue?

Thanks!

4

There are 4 answers

6
MBaas On

Depends on the dialect you're using. Some APL-Implementations support control-strucures, so you could write something like

:If number>100
   ⎕←'Too high'
   →0
:endif
⍳number

In "tradtional APL" you would probably do something like

⍎(number>100)/'⎕←''Too high'' ⋄ →0'
⍳number
0
mappo On

A "classical" way of doing error handling* in APL2 is with the ⎕ES or ⎕EA. Your code would look something like this:

⎕ES(NUMBER>100)/'Too high'
⍳NUMBER

What happens here is that IF the parentheses evaluate to true, THEN the ⎕ES will halt the execution and echo the quoted string.

If you don't want your THEN to terminate, have a look at ⎕EA in some APL documentation.

Please note that I'm on APL2 in a GreenOnBlack environment, so there are likely more neat ways of doing this in a more modern dialect like Dyalog.


*I know you're asking about conditionals and not error handling, but since you're example terminates execution, it might as well be error handling.

There is a crucial difference between this and what MBaas suggests: His solution will gracefully exit the current function which might return a value. Using ⎕ES or ⎕EA with terminate all execution.

4
danb On

If your APL supports control structures then this should work:

∇ generateAll number
:If number>100
   ⎕←'Too high'
:else
   ⎕←⍳ number
:endif
∇

If it does NOT support control structures (like APL2) you will need to branch:

∇ generateAll number
 →(number>100)/error
 ⎕←⍳ number
 →0
error:
 ⎕←'Too high'
∇

You can also use tricks like execute but this is less readable.

2
ein mensch On

In Dyalog APL you have this neat little thing called guards.

They can be used in dfns and evaluate code when a certain condition matches.

func ← {⍵>100 : 'too high' ⋄ 1 : 'number is ok'}