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}}==
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''':
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>{⎕←⍵/'*'}¨⍳5</lang>
<lang APL>stars ← { ⍵ 1 ⍴ {⍵/'*'}¨⍳⍵ }</lang>


However, to stick to the letter of the task description, we can nest an '''each''' inside another one. This becomes less portable as it relies on '''⎕ucs''' to generate a newline, assumes that newline is character 10, and requires support for multiple statements inside an anonymous function (dfn, <tt>{</tt> ... <tt>}</tt>), which e.g. GNU APL does not have:
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
*
**
**
***
***