Loops/For: Difference between revisions
Content added Content deleted
(Simple for loop in Rapira) |
(→{{header|APL}}: Improve nested version portability; add tradfn version with :for) |
||
Line 369: | Line 369: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
For most purposes, the APL analogue of a for loop is the '''each''' operator <tt>¨</tt>. The most natural way to accomplish this task doesn't use a nested '''each''', but the '''repeat''' operator <tt>/</tt> inside a single '''each''': |
|||
<lang APL>{ |
<lang APL>stars ← { ⍵ 1 ⍴ {⍵/'*'}¨⍳⍵ }</lang> |
||
To stick to the letter of the task description, we can nest an '''each''' inside another one, but it's a little silly: |
|||
<lang APL>stars ← { ⍵ 1 ⍴ { {'*'} ¨ ⍳⍵} ¨ ⍳⍵ }</lang> |
|||
Additionally, Dyalog and some other dialects support the more traditional structured programming controls inside a named function definition (tradfn): |
|||
{{works with|Dyalog APL}} |
{{works with|Dyalog APL}} |
||
<lang APL>∇result ← stars count; i; j; vec |
|||
<lang APL>{_←{⍞←'*'}¨⍳⍵ ⋄ ⍞←⎕ucs 10}¨⍳5</lang> |
|||
vec ← ⍬ |
|||
:for i :in ⍳ count |
|||
vec ,← ⊂'' |
|||
:for j :in ⍳ i |
|||
vec[i],←'*' |
|||
:endfor |
|||
:endfor |
|||
result ← count 1 ⍴ vec |
|||
∇</lang> |
|||
{{Out}} |
{{Out}} |
||
The result of all three implementations of `stars` is a column vector, which is displayed like this: |
|||
The output of both versions is the same: |
|||
<pre> |
<pre> stars 5 |
||
* |
|||
** |
** |
||
*** |
*** |