Loops/For: Difference between revisions

→‎{{header|APL}}: Improve nested version portability; add tradfn version with :for
(Simple for loop in Rapira)
(→‎{{header|APL}}: Improve nested version portability; add tradfn version with :for)
Line 369:
 
=={{header|APL}}==
TheFor 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>stars ← {⎕←⍵ ⍵ 1 ⍴ {⍵/'*'}¨⍳5⍳⍵ }</lang>
 
However, toTo stick to the letter of the task description, we can nest an '''each''' inside another one., This becomes less portable asbut it relies on '''⎕ucs''' to generates 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 notlittle havesilly:
 
<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}}
 
<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}}
 
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>* stars 5
*
**
***
1,480

edits