Repeat: Difference between revisions
m (Added output section to Rust impl) |
LalaithMeren (talk | contribs) |
||
(95 intermediate revisions by 50 users not shown) | |||
Line 1: | Line 1: | ||
{{ |
{{task}} |
||
;Task: |
;Task: |
||
Line 6: | Line 6: | ||
The latter procedure is executed a number of times equal to the accepted integer. |
The latter procedure is executed a number of times equal to the accepted integer. |
||
<br><br> |
<br><br> |
||
=={{header|11l}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="11l">F repeat(f, n) |
|||
L 1..n |
|||
f() |
|||
F procedure() |
|||
print(‘Example’) |
|||
repeat(procedure, 3)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Example |
|||
Example |
|||
Example |
|||
</pre> |
|||
=={{header|6502 Assembly}}== |
|||
===Using a trampoline=== |
|||
This routine is a bit messy, and assumes the called routine doesn't clobber the zero-page memory used to maintain it. This can be modified to push/pop those values before/after the routine is executed. |
|||
<syntaxhighlight lang="6502asm">macro RepeatProc,addr,count ;VASM macro syntax |
|||
; input: |
|||
; addr = the label of the routine you wish to call repeatedly |
|||
; count = how many times you want to DO the procedure. 1 = once, 2 = twice, 3 = three times, etc. Enter "0" for 256 times. |
|||
lda #<\addr |
|||
sta z_L ;a label for a zero-page memory address |
|||
lda #>\addr |
|||
sta z_H ;a label for the zero-page memory address immediately after z_L |
|||
lda \count |
|||
jsr doRepeatProc |
|||
endm |
|||
doRepeatProc: |
|||
sta z_C ;another zero-page memory location |
|||
loop_RepeatProc: |
|||
jsr Trampoline_RepeatProc |
|||
dec z_C |
|||
lda z_C |
|||
bne loop_RepeatProc |
|||
rts |
|||
Trampoline_RepeatProc: |
|||
db $6c,z_L,$00 |
|||
;when executed, becomes an indirect JMP to the address stored at z_L and z_H. Some assemblers will let you type |
|||
;JMP (z_L) and it will automatically replace it with the above during the assembly process. |
|||
;This causes an indirect JMP to the routine. Its RTS will return execution to just after the "JSR Trampoline_RepeatProc" |
|||
;and flow into the loop overhead.</syntaxhighlight> |
|||
Once the macro and the underlying subroutine are created, this is very simple to use: |
|||
<syntaxhighlight lang="6502asm">RepeatProc foo,#20 ;perform the subroutine "foo" twenty times.</syntaxhighlight> |
|||
===Using self-modifying code=== |
|||
This version requires that your "wrapper" executes in RAM, so that it can be modified. For this to work, it is assumed that the routine you're using doesn't clobber Y, or require that its parameters are passed in by A or X (so admittedly this method is a bit limited, but if you use the zero page to hold the parameters you can set them up prior to calling the wrapper itself. |
|||
<syntaxhighlight lang="6502asm">RepeatProc: |
|||
;input: low byte of desired function address in A |
|||
; high byte of desired function address in X |
|||
; repeat count in Y |
|||
STA smc_repeatproc+1 |
|||
STX smc_repeatproc+2 |
|||
smc_repeatproc: |
|||
jsr $0000 ;this is modified by the STA and STX above. |
|||
dey |
|||
bne smc_repeatproc |
|||
rts</syntaxhighlight> |
|||
=={{header|68000 Assembly}}== |
|||
This example code prints an exclamation point to the screen 4 times. |
|||
It is assumed that the functions called do not clobber A5 or D7, as doing so would cause undefined behavior (read: a crash or a program counter "escape.") |
|||
<syntaxhighlight lang="68000devpac"> lea foo,a5 ;function to execute |
|||
move.w #4-1,d7 ;times to repeat |
|||
jsr Repeater |
|||
jmp * ;halt the CPU, we're done |
|||
repeater: |
|||
jsr repeaterhelper ;this also need to be a call, so that the RTS of the desired procedure |
|||
;returns us to the loop rather than the line after "jsr Repeater". |
|||
DBRA D7,repeater |
|||
rts |
|||
repeaterhelper: |
|||
jmp (a5) ;keep in mind, this is NOT a dereference, it simply sets the program counter equal to A5. |
|||
;A bit misleading if you ask me. |
|||
foo: |
|||
MOVE.B #'!',D0 |
|||
JSR PrintChar |
|||
rts</syntaxhighlight> |
|||
{{out}} |
|||
<pre>!!!!</pre> |
|||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">DEFINE PTR="CARD" |
|||
PROC OutputText(CHAR ARRAY s) |
|||
PrintE(s) |
|||
RETURN |
|||
PROC Procedure=*(CHAR ARRAY s) |
|||
DEFINE JSR="$20" |
|||
DEFINE RTS="$60" |
|||
[JSR $00 $00 ;JSR to address set by SetProcedure |
|||
RTS] |
|||
PROC SetProcedure(PTR p) |
|||
PTR addr |
|||
addr=Procedure+1 ;location of address of JSR |
|||
PokeC(addr,p) |
|||
RETURN |
|||
PROC Repeat(PTR procFun CHAR ARRAY s BYTE n) |
|||
BYTE i |
|||
SetProcedure(procFun) |
|||
FOR i=1 TO n |
|||
DO |
|||
Procedure(s) |
|||
OD |
|||
RETURN |
|||
PROC Main() |
|||
Repeat(OutputText,"Action!",5) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Repeat.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
Action! |
|||
Action! |
|||
Action! |
|||
Action! |
|||
Action! |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
procedure Repeat_Example is |
procedure Repeat_Example is |
||
Line 27: | Line 164: | ||
begin |
begin |
||
Repeat(Hello'Access, 3); -- Hello'Access points to the procedure Hello |
Repeat(Hello'Access, 3); -- Hello'Access points to the procedure Hello |
||
end Repeat_Example;</ |
end Repeat_Example;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 34: | Line 171: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
||
< |
<syntaxhighlight lang="algol68"> |
||
# operator that executes a procedure the specified number of times # |
# operator that executes a procedure the specified number of times # |
||
OP REPEAT = ( INT count, PROC VOID routine )VOID: |
OP REPEAT = ( INT count, PROC VOID routine )VOID: |
||
Line 60: | Line 197: | ||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 70: | Line 207: | ||
+3 +9 |
+3 +9 |
||
</pre> |
</pre> |
||
=={{header|ALGOL W}}== |
|||
As well as the names of procedures, Algol W allows statements to be passed as parameters where a procedure is expected. |
|||
<syntaxhighlight lang="algolw">begin |
|||
% executes the procedure routine the specified number of times % |
|||
procedure repeat ( integer value count; procedure routine ) ; |
|||
for i := 1 until count do routine; |
|||
begin |
|||
integer x; |
|||
% print "hello" three times % |
|||
repeat( 3, write( "hello" ) ); |
|||
% print the first 10 squares % |
|||
write(); |
|||
x := 1; |
|||
repeat( 10 |
|||
, begin |
|||
writeon( i_w := s_w := 1, x * x ); |
|||
x := x + 1 |
|||
end |
|||
) |
|||
end |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
hello |
|||
hello |
|||
hello |
|||
1 4 9 16 25 36 49 64 81 100 |
|||
</pre> |
|||
=={{header|AppleScript}}== |
|||
<syntaxhighlight lang="applescript">-- applyN :: Int -> (a -> a) -> a -> a |
|||
on applyN(n, f, x) |
|||
script go |
|||
on |λ|(a, g) |
|||
|λ|(a) of mReturn(g) |
|||
end |λ| |
|||
end script |
|||
foldl(go, x, replicate(n, f)) |
|||
end applyN |
|||
-------- SAMPLE FUNCTIONS FOR REPEATED APPLICATION -------- |
|||
on double(x) |
|||
2 * x |
|||
end double |
|||
on plusArrow(s) |
|||
s & " -> " |
|||
end plusArrow |
|||
on squareRoot(n) |
|||
n ^ 0.5 |
|||
end squareRoot |
|||
-------------------------- TESTS -------------------------- |
|||
on run |
|||
log applyN(10, double, 1) |
|||
--> 1024 |
|||
log applyN(5, plusArrow, "") |
|||
--> " -> -> -> -> -> " |
|||
log applyN(3, squareRoot, 65536) |
|||
--> 4.0 |
|||
end run |
|||
-------------------- GENERIC FUNCTIONS -------------------- |
|||
-- foldl :: (a -> b -> a) -> a -> [b] -> a |
|||
on foldl(f, startValue, xs) |
|||
tell mReturn(f) |
|||
set v to startValue |
|||
set lng to length of xs |
|||
repeat with i from 1 to lng |
|||
set v to |λ|(v, item i of xs, i, xs) |
|||
end repeat |
|||
return v |
|||
end tell |
|||
end foldl |
|||
-- mReturn :: First-class m => (a -> b) -> m (a -> b) |
|||
on mReturn(f) |
|||
-- 2nd class handler function lifted into 1st class script wrapper. |
|||
if script is class of f then |
|||
f |
|||
else |
|||
script |
|||
property |λ| : f |
|||
end script |
|||
end if |
|||
end mReturn |
|||
-- Egyptian multiplication - progressively doubling a list, appending |
|||
-- stages of doubling to an accumulator where needed for binary |
|||
-- assembly of a target length |
|||
-- replicate :: Int -> a -> [a] |
|||
on replicate(n, a) |
|||
set out to {} |
|||
if 1 > n then return out |
|||
set dbl to {a} |
|||
repeat while (1 < n) |
|||
if 0 < (n mod 2) then set out to out & dbl |
|||
set n to (n div 2) |
|||
set dbl to (dbl & dbl) |
|||
end repeat |
|||
return out & dbl |
|||
end replicate</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>(*1024*) |
|||
(* -> -> -> -> -> *) |
|||
(*4.0*)</pre> |
|||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
http://hoop-la.ca/apple2/2016/winterwarmup/#repeat.bas |
https://web.archive.org/web/20190202165511/http://hoop-la.ca/apple2/2016/winterwarmup/#repeat.bas |
||
<syntaxhighlight> 100 FOR I = 768 TO 794 |
|||
110 READ B: POKE I,B: NEXT |
|||
120 DATA165,185,72,165,184,72 |
|||
130 DATA165,118,72,165,117,72 |
|||
140 DATA169,176,72,32,123,221 |
|||
150 DATA32,82,231,32,65,217 |
|||
160 DATA76,210,215 |
|||
170 POKE 1014,0: POKE 1015,3 |
|||
200 LET P = 400:N = 4 |
|||
210 GOSUB 300"REPEAT P N |
|||
220 END |
|||
300 IF N < = 0 THEN RETURN |
|||
310 LET N = N - 1 |
|||
320 & P |
|||
330 GOTO 300 |
|||
400 PRINT "EXAMPLE" |
|||
410 RETURN |
|||
</syntaxhighlight> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">print "---------------------------" |
|||
print "As a loop" |
|||
print "---------------------------" |
|||
loop 4 'x -> |
|||
print "Example 1" |
|||
repeatFunc: function [f,times][ |
|||
loop times 'x -> |
|||
do f |
|||
] |
|||
print "---------------------------" |
|||
print "With a block param" |
|||
print "---------------------------" |
|||
repeatFunc [print "Example 2"] 4 |
|||
repeatFunc: function [f,times][ |
|||
loop times 'x -> |
|||
f |
|||
] |
|||
print "---------------------------" |
|||
print "With a function param" |
|||
print "---------------------------" |
|||
repeatFunc $[][print "Example 3"] 4</syntaxhighlight> |
|||
{{out}} |
|||
<pre>--------------------------- |
|||
As a loop |
|||
--------------------------- |
|||
Example 1 |
|||
Example 1 |
|||
Example 1 |
|||
Example 1 |
|||
--------------------------- |
|||
With a block param |
|||
--------------------------- |
|||
Example 2 |
|||
Example 2 |
|||
Example 2 |
|||
Example 2 |
|||
--------------------------- |
|||
With a function param |
|||
--------------------------- |
|||
Example 3 |
|||
Example 3 |
|||
Example 3 |
|||
Example 3</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">repeat("fMsgBox",3) |
||
return |
return |
||
Line 85: | Line 412: | ||
fMsgBox(){ |
fMsgBox(){ |
||
MsgBox hello |
MsgBox hello |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f REPEAT.AWK |
# syntax: GAWK -f REPEAT.AWK |
||
BEGIN { |
BEGIN { |
||
Line 107: | Line 434: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
<p>output:</p> |
<p>output:</p> |
||
<pre> |
<pre> |
||
Line 117: | Line 444: | ||
inside odd 3 |
inside odd 3 |
||
</pre> |
</pre> |
||
=={{header|BASIC}}== |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="vb">subroutine proc() |
|||
print " Inside loop" |
|||
end subroutine |
|||
subroutine repeat(func, times) |
|||
for i = 1 to times |
|||
call proc() |
|||
next |
|||
end subroutine |
|||
call repeat("proc", 5) |
|||
print "Loop Ended</syntaxhighlight> |
|||
{{out}} |
|||
<pre> Inside loop |
|||
Inside loop |
|||
Inside loop |
|||
Inside loop |
|||
Inside loop |
|||
Loop Ended</pre> |
|||
==={{header|Chipmunk Basic}}=== |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
<syntaxhighlight lang="qbasic">10 sub proc() |
|||
20 print " Inside loop" |
|||
30 end sub |
|||
40 sub repeat(func$,times) |
|||
50 for i = 1 to times |
|||
60 proc() |
|||
70 next i |
|||
80 end sub |
|||
90 repeat("proc",5) |
|||
100 print "Loop Ended" |
|||
110 end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as BASIC256 entry.</pre> |
|||
==={{header|GW-BASIC}}=== |
|||
{{works with|BASICA}} |
|||
{{works with|Chipmunk Basic}} |
|||
{{works with|Just BASIC}} |
|||
{{works with|Minimal BASIC}} |
|||
{{works with|MSX BASIC|any}} |
|||
{{works with|PC-BASIC|any}} |
|||
{{works with|QBasic}} |
|||
{{works with|Quite BASIC}} |
|||
<syntaxhighlight lang="qbasic">100 let f$ = "proc" |
|||
110 let c = 5 |
|||
120 gosub 170 |
|||
130 print "Loop Ended" |
|||
140 goto 220 |
|||
150 print " Inside loop" |
|||
160 return |
|||
170 rem repeat(f$,c) |
|||
180 for i = 1 to c |
|||
190 gosub 150 |
|||
200 next i |
|||
210 return |
|||
220 end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as BASIC256 entry.</pre> |
|||
==={{header|Minimal BASIC}}=== |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|MSX Basic}}=== |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|QBasic}}=== |
|||
{{works with|QBasic|1.1}} |
|||
{{works with|QuickBasic|4.5}} |
|||
<syntaxhighlight lang="qbasic">DECLARE SUB rep (func AS STRING, c AS INTEGER) |
|||
DECLARE SUB proc () |
|||
CALL rep("proc", 5) |
|||
PRINT "Loop Ended" |
|||
SUB proc |
|||
PRINT " Inside loop" |
|||
END SUB |
|||
SUB rep (func AS STRING, c AS INTEGER) |
|||
FOR i = 1 TO c |
|||
proc |
|||
NEXT |
|||
END SUB</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as BASIC256 entry.</pre> |
|||
==={{header|Quite BASIC}}=== |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|True BASIC}}=== |
|||
<syntaxhighlight lang="qbasic">SUB proc |
|||
PRINT " Inside loop" |
|||
END SUB |
|||
SUB rep (func$, c) |
|||
FOR i = 1 to c |
|||
CALL proc |
|||
NEXT i |
|||
END SUB |
|||
CALL rep ("proc", 5) |
|||
PRINT "Loop Ended" |
|||
END</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as BASIC256 entry.</pre> |
|||
==={{header|XBasic}}=== |
|||
{{works with|Windows XBasic}} |
|||
<syntaxhighlight lang="qbasic">PROGRAM "Repeat" |
|||
VERSION "0.0000" |
|||
DECLARE FUNCTION Entry () |
|||
DECLARE FUNCTION Proc () |
|||
DECLARE FUNCTION Repe (func$, c) |
|||
FUNCTION Entry () |
|||
Repe ("proc", 5) |
|||
PRINT "Loop Ended" |
|||
END FUNCTION |
|||
FUNCTION Proc () |
|||
PRINT " Inside loop" |
|||
END FUNCTION |
|||
FUNCTION Repe (func$, c) |
|||
FOR i = 1 TO c |
|||
Proc () |
|||
NEXT i |
|||
END FUNCTION |
|||
END PROGRAM</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as BASIC256 entry.</pre> |
|||
=={{header|Batch File}}== |
|||
<syntaxhighlight lang="dos"> |
|||
@echo off |
|||
:_main |
|||
setlocal |
|||
call:_func1 _func2 3 |
|||
pause>nul |
|||
exit/b |
|||
:_func1 |
|||
setlocal enabledelayedexpansion |
|||
for /l %%i in (1,1,%2) do call:%1 |
|||
exit /b |
|||
:_func2 |
|||
setlocal |
|||
echo _func2 has been executed |
|||
exit /b |
|||
</syntaxhighlight> |
|||
=={{header|BQN}}== |
|||
BQN has a builtin called Repeat which fulfills the criteria for the challenge(and allows multiple iteration counts), hence there is a recursive implementation of repeat added in as well. |
|||
<syntaxhighlight lang="bqn">•Show {2+𝕩}⍟3 1 |
|||
_repeat_ ← {(𝕘>0)◶⊢‿(𝔽_𝕣_(𝕘-1)𝔽)𝕩} |
|||
•Show {2+𝕩} _repeat_ 3 1</syntaxhighlight><syntaxhighlight lang="text">7 |
|||
7</syntaxhighlight> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
void repeat(void (*f)(void), unsigned int n) { |
void repeat(void (*f)(void), unsigned int n) { |
||
Line 133: | Line 631: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C sharp|C#}}== |
|||
{{trans|Java}} |
|||
<syntaxhighlight lang="csharp">using System; |
|||
namespace Repeat { |
|||
class Program { |
|||
static void Repeat(int count, Action<int> fn) { |
|||
if (null == fn) { |
|||
throw new ArgumentNullException("fn"); |
|||
} |
|||
for (int i = 0; i < count; i++) { |
|||
fn.Invoke(i + 1); |
|||
} |
|||
} |
|||
static void Main(string[] args) { |
|||
Repeat(3, x => Console.WriteLine("Example {0}", x)); |
|||
} |
|||
} |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Example 1 |
|||
Example 2 |
|||
Example 3</pre> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">template <typename Function> |
||
void repeat(Function f, unsigned int n) { |
void repeat(Function f, unsigned int n) { |
||
for(unsigned int i=n; 0<i; i--) |
for(unsigned int i=n; 0<i; i--) |
||
f(); |
f(); |
||
}</ |
}</syntaxhighlight> |
||
usage: |
usage: |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
void example() { |
void example() { |
||
std::cout << "Example\n"; |
std::cout << "Example\n"; |
||
} |
} |
||
repeat(example, 4);</ |
repeat(example, 4);</syntaxhighlight> |
||
{{works with|C++11}} |
{{works with|C++11}} |
||
< |
<syntaxhighlight lang="cpp"> repeat([]{std::cout << "Example\n";}, 4);</syntaxhighlight> |
||
=={{header|Chapel}}== |
|||
The most basic form, with generics. |
|||
<syntaxhighlight lang="chapel"> |
|||
config const n = 5; |
|||
proc example() |
|||
{ |
|||
writeln("example"); |
|||
} |
|||
proc repeat(func, n) |
|||
{ |
|||
for i in 0..#n do func(); |
|||
} |
|||
repeat(example, n); |
|||
</syntaxhighlight> |
|||
With argument type hinting. |
|||
<syntaxhighlight lang="chapel"> |
|||
config const n = 5; |
|||
proc example() |
|||
{ |
|||
writeln("example"); |
|||
} |
|||
proc repeat(func : proc(), n : uint) |
|||
{ |
|||
for i in 0..#n do func(); |
|||
} |
|||
repeat(example, n); |
|||
</syntaxhighlight> |
|||
Example of passing function which takes arguments. Chapel does not allow functions with generic arguments to be passed. First-class functions are still in development: https://chapel-lang.org/docs/technotes/firstClassProcedures.html |
|||
<syntaxhighlight lang="chapel"> |
|||
config const n = 5; |
|||
proc example(x : uint) |
|||
{ |
|||
writeln("example ", x); |
|||
} |
|||
proc repeat(func : proc(x : uint), n : uint) |
|||
{ |
|||
for i in 0..#n do func(i); |
|||
} |
|||
repeat(example, n); |
|||
</syntaxhighlight> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(defn repeat-function [f n] |
||
(dotimes [i n] (f)))</ |
(dotimes [i n] (f)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 161: | Line 738: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun repeat (f n) |
||
(dotimes (i n) (funcall f))) |
(dotimes (i n) (funcall f))) |
||
(repeat (lambda () (format T "Example~%")) 5)</ |
(repeat (lambda () (format T "Example~%")) 5)</syntaxhighlight> |
||
=={{header|Cowgol}}== |
|||
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
|||
# Only functions that implement an interface can be passed around |
|||
# The interface is a type and must be defined before it is used |
|||
# This defines an interface for a function that takes no arguments |
|||
interface Fn(); |
|||
# This function repeats a function that implements Fn |
|||
sub Repeat(f: Fn, n: uint32) is |
|||
while n != 0 loop |
|||
f(); |
|||
n := n - 1; |
|||
end loop; |
|||
end sub; |
|||
# Here is a function |
|||
sub Foo implements Fn is |
|||
print("foo "); |
|||
end sub; |
|||
# Prints "foo foo foo foo" |
|||
Repeat(Foo, 4); |
|||
print_nl(); </syntaxhighlight> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void repeat(void function() fun, in uint times) { |
||
foreach (immutable _; 0 .. times) |
foreach (immutable _; 0 .. times) |
||
fun(); |
fun(); |
||
Line 179: | Line 781: | ||
void main() { |
void main() { |
||
repeat(&procedure, 3); |
repeat(&procedure, 3); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Example |
<pre>Example |
||
Example |
Example |
||
Example</pre> |
Example</pre> |
||
=={{header|Delphi}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
program Repeater; |
|||
{$APPTYPE CONSOLE} |
|||
{$R *.res} |
|||
type |
|||
TSimpleProc = procedure; // Can also define types for procedures (& functions) which |
|||
// require params. |
|||
procedure Once; |
|||
begin |
|||
writeln('Hello World'); |
|||
end; |
|||
procedure Iterate(proc : TSimpleProc; Iterations : integer); |
|||
var |
|||
i : integer; |
|||
begin |
|||
for i := 1 to Iterations do |
|||
proc; |
|||
end; |
|||
begin |
|||
Iterate(Once, 3); |
|||
readln; |
|||
end. |
|||
</syntaxhighlight> |
|||
Alternative |
|||
<syntaxhighlight lang="delphi"> |
|||
program Repeater; |
|||
{$APPTYPE CONSOLE} |
|||
{$R *.res} |
|||
uses |
|||
System.SysUtils; |
|||
procedure Iterate(proc: TProc; Iterations: integer); |
|||
var |
|||
i: integer; |
|||
begin |
|||
for i := 1 to Iterations do |
|||
proc; |
|||
end; |
|||
begin |
|||
Iterate( |
|||
procedure |
|||
begin |
|||
writeln('Hello World'); |
|||
end, 3); |
|||
readln; |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Hello World |
|||
Hello World |
|||
Hello World</pre> |
|||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(define (repeat f n) (for ((i n)) (f))) |
(define (repeat f n) (for ((i n)) (f))) |
||
Line 200: | Line 868: | ||
(cos 0.7390851332151605) |
(cos 0.7390851332151605) |
||
→ 0.7390851332151608 ;; fixed point found |
→ 0.7390851332151608 ;; fixed point found |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F#|F sharp}}== |
|||
<syntaxhighlight lang="fsharp">open System |
|||
let Repeat c f = |
|||
for _ in 1 .. c do |
|||
f() |
|||
let Hello _ = |
|||
printfn "Hello world" |
|||
[<EntryPoint>] |
|||
let main _ = |
|||
Repeat 3 Hello |
|||
0 // return an integer exit code</syntaxhighlight> |
|||
=={{header|Factor}}== |
|||
Factor comes with the <tt>times</tt> word which does exactly this. For example, |
|||
<syntaxhighlight lang="factor">3 [ "Hello!" print ] times</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Hello! |
|||
Hello! |
|||
Hello! |
|||
</pre> |
|||
The implementation of <tt>times</tt>: |
|||
<syntaxhighlight lang="factor">: times ( ... n quot: ( ... -- ... ) -- ... ) |
|||
[ drop ] prepose each-integer ; inline</syntaxhighlight> |
|||
=={{header|Fe}}== |
|||
<syntaxhighlight lang="clojure"> |
|||
(= repeat (mac (i n . body) |
|||
(list 'do |
|||
(list 'let i 0) |
|||
(list 'while (list '< i n) |
|||
(list '= i (list '+ i 1)) |
|||
(cons 'do body))))) |
|||
; print multiplication table |
|||
(repeat i 10 |
|||
(repeat j 10 |
|||
(print i "x" j "=" (* i j))) |
|||
(print)) |
|||
</syntaxhighlight> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: times ( xt n -- ) |
||
0 ?do dup execute loop drop ;</ |
0 ?do dup execute loop drop ;</syntaxhighlight> |
||
Or, taking care to keep the data stack clean for the XT's use, as is often desired: |
Or, taking care to keep the data stack clean for the XT's use, as is often desired: |
||
< |
<syntaxhighlight lang="forth">: times { xt n -- } |
||
n 0 ?do xt execute loop ;</ |
n 0 ?do xt execute loop ;</syntaxhighlight> |
||
Or as a novel control structure, which is not demanded by this task but which is just as idiomatic in Forth as the XT-consuming alternatives above: |
Or as a novel control structure, which is not demanded by this task but which is just as idiomatic in Forth as the XT-consuming alternatives above: |
||
< |
<syntaxhighlight lang="forth">: times[ ]] 0 ?do [[ ; immediate compile-only |
||
: ]times postpone loop ; immediate compile-only</ |
: ]times postpone loop ; immediate compile-only</syntaxhighlight> |
||
Usage: |
Usage: |
||
< |
<syntaxhighlight lang="forth">[: cr ." Hello" ;] 3 times |
||
: 3-byes ( -- ) 3 times[ cr ." Bye" ]times ; |
: 3-byes ( -- ) 3 times[ cr ." Bye" ]times ; |
||
3-byes</ |
3-byes</syntaxhighlight> |
||
{{out}}<pre>Hello |
{{out}}<pre>Hello |
||
Line 230: | Line 943: | ||
Bye |
Bye |
||
Bye</pre> |
Bye</pre> |
||
=={{header|FreeBASIC}}== |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
Sub proc() |
|||
Print " proc called" |
|||
End Sub |
|||
Sub repeat(s As Sub, n As UInteger) |
|||
For i As Integer = 1 To n |
|||
Print Using "##"; i; |
|||
s() |
|||
Next |
|||
End Sub |
|||
repeat(@proc, 5) |
|||
Print |
|||
Print "Press any key to quit" |
|||
Sleep</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 proc called |
|||
2 proc called |
|||
3 proc called |
|||
4 proc called |
|||
5 proc called |
|||
</pre> |
|||
=={{header|FutureBasic}}== |
|||
<syntaxhighlight lang="futurebasic"> |
|||
include "NSLog.incl" |
|||
void local fn Example( value as long ) |
|||
NSLog(@"Example %ld",value) |
|||
end fn |
|||
void local fn DoIt( fnAddress as ptr, count as long ) |
|||
def fn Repeat( j as long ) using fnAddress |
|||
long i |
|||
for i = 1 to count |
|||
fn Repeat( i ) |
|||
next |
|||
end fn |
|||
fn DoIt( @fn Example, 3 ) |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Example 1 |
|||
Example 2 |
|||
Example 3 |
|||
</pre> |
|||
=={{header|Gambas}}== |
|||
Note: Gambas (3.14.0) cannot perform this task as specified, as it does not have delegates, and pointers do not seem to work with procedures. What does work is using Object.Call, which is intended for executing procedures from external libraries. However the accepting procedure must refer to the object containing the procedure, and refer to the procedure by a String name. In this case, the current module/class reference (Me) is used, but the String name must be passed. This arrangement will only work within the same module/class. It may be possible to pass the parent reference to a method (taking 3 parameters) in another class if the named procedure is Public. The empty array ([]) in Object.Call represent a procedure without parameters, which are not an explicit requirement for this Task, but might require another parameter to the accepting procedure. |
|||
<syntaxhighlight lang="gambas"> |
|||
Public Sub Main() |
|||
RepeatIt("RepeatableOne", 2) |
|||
RepeatIt("RepeatableTwo", 3) |
|||
End |
|||
'Cannot pass procedure pointer in Gambas; must pass procedure name and use Object.Call() |
|||
Public Sub RepeatIt(sDelegateName As String, iCount As Integer) |
|||
For iCounter As Integer = 1 To iCount |
|||
Object.Call(Me, sDelegateName, []) |
|||
Next |
|||
End |
|||
Public Sub RepeatableOne() |
|||
Print "RepeatableOne" |
|||
End |
|||
Public Sub RepeatableTwo() |
|||
Print "RepeatableTwo" |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
RepeatableOne |
|||
RepeatableOne |
|||
RepeatableTwo |
|||
RepeatableTwo |
|||
RepeatableTwo |
|||
</pre> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 248: | Line 1,058: | ||
func main() { |
func main() { |
||
repeat(4, fn) |
repeat(4, fn) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Such a function already exists |
Such a function already exists |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad (replicateM_) |
||
sampleFunction :: IO () |
sampleFunction :: IO () |
||
sampleFunction = putStrLn "a" |
sampleFunction = putStrLn "a" |
||
main = replicateM_ 5 sampleFunction</ |
main = replicateM_ 5 sampleFunction</syntaxhighlight> |
||
And if the requirement is for something like a Church numeral, compounding the application of a given function '''n''' times (rather than repeating the same IO event '''n''' times) then we could also write something like '''applyN''' below: |
|||
<syntaxhighlight lang="haskell">applyN :: Int -> (a -> a) -> a -> a |
|||
applyN n f = foldr (.) id (replicate n f) |
|||
main :: IO () |
|||
main = print $ applyN 10 (\x -> 2 * x) 1</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>1024</pre> |
|||
=={{header|Isabelle}}== |
|||
Isabelle does not have procedures with side effects. So we cannot do things such as printing a string to stdout. Isabelle only has pure mathematical functions. |
|||
<syntaxhighlight lang="isabelle">theory Scratch |
|||
imports Main |
|||
begin |
|||
text‹ |
|||
Given the function we want to execute multiple times is of |
|||
type \<^typ>‹unit ⇒ unit›. |
|||
› |
|||
fun pure_repeat :: "(unit ⇒ unit) ⇒ nat ⇒ unit" where |
|||
"pure_repeat _ 0 = ()" |
|||
| "pure_repeat f (Suc n) = f (pure_repeat f n)" |
|||
text‹ |
|||
Functions are pure in Isabelle. They don't have side effects. |
|||
This means, the \<^const>‹pure_repeat› we implemented is always equal |
|||
to \<^term>‹() :: unit›, independent of the function \<^typ>‹unit ⇒ unit› |
|||
or \<^typ>‹nat›. |
|||
Technically, functions are not even "executed", but only evaluated. |
|||
› |
|||
lemma "pure_repeat f n = ()" by simp |
|||
text‹ |
|||
But we can repeat a value of \<^typ>‹'a› \<^term>‹n› times and return the result |
|||
in a list of length \<^term>‹n› |
|||
› |
|||
fun repeat :: "'a ⇒ nat ⇒ 'a list" where |
|||
"repeat _ 0 = []" |
|||
| "repeat f (Suc n) = f # (repeat f n)" |
|||
lemma "repeat ''Hello'' 4 = [''Hello'', ''Hello'', ''Hello'', ''Hello'']" |
|||
by code_simp |
|||
lemma "length (repeat a n) = n" by(induction n) simp+ |
|||
text‹ |
|||
Technically, \<^typ>‹'a› is not a function. We can wrap it in a dummy function |
|||
which takes a \<^typ>‹unit› as first argument. This gives a function of type |
|||
\<^typ>‹unit ⇒ 'a›. |
|||
› |
|||
fun fun_repeat :: "(unit ⇒ 'a) ⇒ nat ⇒ 'a list" where |
|||
"fun_repeat _ 0 = []" |
|||
| "fun_repeat f (Suc n) = (f ()) # (fun_repeat f n)" |
|||
lemma "fun_repeat (λ_. ''Hello'') 4 = |
|||
[''Hello'', ''Hello'', ''Hello'', ''Hello'']" |
|||
by code_simp |
|||
text‹ |
|||
Yet, \<^const>‹fun_repeat› with the dummy function \<^typ>‹unit ⇒ 'a› is |
|||
equivalent to \<^const>‹repeat› with the value \<^typ>‹'a› directly. |
|||
› |
|||
lemma "fun_repeat (λ_. a) n = repeat a n" by(induction n) simp+ |
|||
end</syntaxhighlight> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
<syntaxhighlight lang="j"> |
|||
<lang J> |
|||
NB. ^: (J's power conjunction) repeatedly evaluates a verb. |
NB. ^: (J's power conjunction) repeatedly evaluates a verb. |
||
Line 314: | Line 1,191: | ||
hi |
hi |
||
hi |
hi |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
There are two ways to achieve this, one way is through ''reflection''. |
|||
<syntaxhighlight lang="java"> |
|||
import java.lang.reflect.Method; |
|||
public class Program { |
|||
public static void main(String[] args) throws ReflectiveOperationException { |
|||
Method method = Program.class.getMethod("printRosettaCode"); |
|||
repeat(method, 5); |
|||
} |
|||
public static void printRosettaCode() { |
|||
System.out.println("Rosetta Code"); |
|||
} |
|||
public static void repeat(Method method, int count) throws ReflectiveOperationException { |
|||
while (count-- > 0) |
|||
method.invoke(null); |
|||
} |
|||
}</syntaxhighlight> |
|||
<pre> |
|||
Rosetta Code |
|||
Rosetta Code |
|||
Rosetta Code |
|||
Rosetta Code |
|||
Rosetta Code |
|||
</pre> |
|||
<br /> |
|||
Or |
|||
{{works with|Java|8}} |
{{works with|Java|8}} |
||
< |
<syntaxhighlight lang="java">import java.util.function.Consumer; |
||
import java.util.stream.IntStream; |
import java.util.stream.IntStream; |
||
Line 330: | Line 1,235: | ||
IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); |
IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 337: | Line 1,242: | ||
Example 2 |
Example 2 |
||
Example 3</pre> |
Example 3</pre> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
{{works with|jq|1.4}} |
{{works with|jq|1.4}} |
||
Line 351: | Line 1,257: | ||
'''Unoptimized version''': |
'''Unoptimized version''': |
||
< |
<syntaxhighlight lang="jq">def unoptimized_repeat(f; n): |
||
if n <= 0 then empty |
if n <= 0 then empty |
||
else f, repeat(f; n-1) |
else f, repeat(f; n-1) |
||
end;</ |
end;</syntaxhighlight> |
||
'''Optimized for TCO''': |
'''Optimized for TCO''': |
||
< |
<syntaxhighlight lang="jq">def repeat(f; n): |
||
# state: [count, in] |
# state: [count, in] |
||
def r: |
def r: |
||
if .[0] >= n then empty else (.[1] | f), (.[0] += 1 | r) end; |
if .[0] >= n then empty else (.[1] | f), (.[0] += 1 | r) end; |
||
[0, .] | r;</ |
[0, .] | r;</syntaxhighlight> |
||
'''Variant''': |
'''Variant''': |
||
< |
<syntaxhighlight lang="jq"># If n is a non-negative integer, |
||
# then emit a stream of (n + 1) terms: ., f, f|f, f|f|f, ... |
# then emit a stream of (n + 1) terms: ., f, f|f, f|f|f, ... |
||
def repeatedly(f; n): |
def repeatedly(f; n): |
||
Line 371: | Line 1,277: | ||
else .[1], ([.[0] - 1, (.[1] | f)] | r) |
else .[1], ([.[0] - 1, (.[1] | f)] | r) |
||
end; |
end; |
||
[n, .] | r;</ |
[n, .] | r;</syntaxhighlight> |
||
'''Examples''': |
'''Examples''': |
||
< |
<syntaxhighlight lang="jq">0 | [ repeat(.+1; 3) ]</syntaxhighlight> |
||
produces: |
produces: |
||
[1,1,1] |
[1,1,1] |
||
< |
<syntaxhighlight lang="jq">0 | repeatedly(.+1; 3)</syntaxhighlight> |
||
produces: |
produces: |
||
0 |
0 |
||
Line 385: | Line 1,291: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">function sayHi() |
||
println("Hi") |
println("Hi") |
||
end |
end |
||
Line 393: | Line 1,299: | ||
end |
end |
||
rep(sayHi, 3)</ |
rep(sayHi, 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hi |
<pre>Hi |
||
Hi |
Hi |
||
Hi</pre> |
Hi</pre> |
||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="scala">// version 1.0.6 |
|||
fun repeat(n: Int, f: () -> Unit) { |
|||
for (i in 1..n) { |
|||
f() |
|||
println(i) |
|||
} |
|||
} |
|||
fun main(args: Array<String>) { |
|||
repeat(5) { print("Example ") } |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Example 1 |
|||
Example 2 |
|||
Example 3 |
|||
Example 4 |
|||
Example 5 |
|||
</pre> |
|||
=={{header|Lean}}== |
|||
===Lean 3.4.2=== |
|||
<syntaxhighlight lang="lean"> |
|||
def repeat : ℕ → (ℕ → string) → string |
|||
| 0 f := "done" |
|||
| (n + 1) f := (f n) ++ (repeat n f) |
|||
#eval repeat 5 $ λ b : ℕ , "me " |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
"me me me me me done" |
|||
</pre> |
|||
===Lean 4=== |
|||
<syntaxhighlight lang="lean"> |
|||
def repeatf (f : Nat -> String) (n : Nat) : String := |
|||
match n with |
|||
| 0 => "." |
|||
| (k + 1) => (f k) ++ (repeatf f k) |
|||
def example1 : String := |
|||
repeatf (fun (x : Nat) => toString (x) ++ " ") (10) |
|||
#eval example1 |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
"9 8 7 6 5 4 3 2 1 0 ." |
|||
</pre> |
|||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">rep "answer",3 |
||
command rep x,n |
command rep x,n |
||
Line 406: | Line 1,370: | ||
do merge("[[x]] [[n]]") |
do merge("[[x]] [[n]]") |
||
end repeat |
end repeat |
||
end rep</ |
end rep</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
No particular magic required as Lua allows functions to be passed as arguments. |
No particular magic required as Lua allows functions to be passed as arguments. |
||
< |
<syntaxhighlight lang="lua">function myFunc () |
||
print("Sure looks like a function in here...") |
print("Sure looks like a function in here...") |
||
end |
end |
||
Line 421: | Line 1,385: | ||
rep(myFunc, 4) |
rep(myFunc, 4) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Sure looks like a function in here... |
<pre>Sure looks like a function in here... |
||
Line 428: | Line 1,392: | ||
Sure looks like a function in here...</pre> |
Sure looks like a function in here...</pre> |
||
=={{header| |
=={{header|Mastermind}}== |
||
Functions are in-lined at compile time in [[Mastermind]], meaning the "repeat" function cannot accept another procedure as an argument. This is due to limitations of the compilation target, which is [[Brainf***]]. Dynamically calling functions would require creating a function runtime. |
|||
<syntaxhighlight lang="mastermind">def do_something<number> { |
|||
output "Letter: "; |
|||
output 'a' + number; |
|||
output '\n'; |
|||
} |
|||
def repeat<times> { |
|||
let i = 0; |
|||
drain times into i { |
|||
do_something<i>; |
|||
} |
|||
} |
|||
let repetitions = 8; |
|||
repeat<repetitions>;</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Letter: a |
|||
Letter: b |
|||
Letter: c |
|||
Letter: d |
|||
Letter: e |
|||
Letter: f |
|||
Letter: g |
|||
Letter: h |
|||
</pre> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
Note that anything of this form is not considered good practice. |
Note that anything of this form is not considered good practice. |
||
< |
<syntaxhighlight lang="mathematica">repeat[f_, n_] := Do[f[], {n}]; |
||
repeat[Print["Hello, world!"] &, 5];</ |
repeat[Print["Hello, world!"] &, 5];</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hello, world! |
<pre>Hello, world! |
||
Line 438: | Line 1,430: | ||
Hello, world! |
Hello, world! |
||
Hello, world!</pre> |
Hello, world!</pre> |
||
=={{header|min}}== |
|||
This operator already exists in min and is called <code>times</code>. |
|||
{{works with|min|0.19.6}} |
|||
<syntaxhighlight lang="min">("Hello" puts!) 3 times</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Hello |
|||
Hello |
|||
Hello |
|||
</pre> |
|||
=={{header|MiniScript}}== |
|||
<syntaxhighlight lang="miniscript">sayHi = function() |
|||
print "Hi!" |
|||
end function |
|||
rep = function(f, n) |
|||
for i in range(1, n) |
|||
f |
|||
end for |
|||
end function |
|||
rep @sayHi, 3</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Hi! |
|||
Hi! |
|||
Hi!</pre> |
|||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>1 П4 |
<syntaxhighlight lang="text">1 П4 |
||
3 ^ 1 6 ПП 09 С/П |
3 ^ 1 6 ПП 09 С/П |
||
Line 447: | Line 1,468: | ||
П7 <-> П0 КПП7 L0 12 В/О |
П7 <-> П0 КПП7 L0 12 В/О |
||
ИП4 С/П КИП4 В/О</ |
ИП4 С/П КИП4 В/О</syntaxhighlight> |
||
=={{header|Modula-2}}== |
|||
<syntaxhighlight lang="modula2">MODULE Repeat; |
|||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
|||
TYPE F = PROCEDURE; |
|||
PROCEDURE Repeat(fun : F; c : INTEGER); |
|||
VAR i : INTEGER; |
|||
BEGIN |
|||
FOR i:=1 TO c DO |
|||
fun |
|||
END |
|||
END Repeat; |
|||
PROCEDURE Print; |
|||
BEGIN |
|||
WriteString("Hello"); |
|||
WriteLn |
|||
END Print; |
|||
BEGIN |
|||
Repeat(Print, 3); |
|||
ReadChar |
|||
END Repeat.</syntaxhighlight> |
|||
=={{header|Nanoquery}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="nanoquery">def repeat(f,n) |
|||
for i in range(1, n) |
|||
f() |
|||
end |
|||
end |
|||
def procedure() |
|||
println "Example" |
|||
end |
|||
repeat(procedure, 3)</syntaxhighlight> |
|||
=={{header|Nim}}== |
|||
<syntaxhighlight lang="nim">proc example = |
|||
echo "Example" |
|||
# Ordinary procedure |
|||
proc repeatProc(fn: proc, n: int) = |
|||
for x in 0..<n: |
|||
fn() |
|||
repeatProc(example, 4) |
|||
# Template (code substitution), simplest form of metaprogramming |
|||
# that Nim has |
|||
template repeatTmpl(n: int, body: untyped): untyped = |
|||
for x in 0..<n: |
|||
body |
|||
# This gets rewritten into a for loop |
|||
repeatTmpl 4: |
|||
example() |
|||
import std/macros |
|||
# A macro which takes some code block and returns code |
|||
# with that code block repeated n times. Macros run at |
|||
# compile-time |
|||
macro repeatMacro(n: static[int], body: untyped): untyped = |
|||
result = newStmtList() |
|||
for x in 0..<n: |
|||
result.add body |
|||
# This gets rewritten into 4 calls to example() |
|||
# at compile-time |
|||
repeatMacro 4: |
|||
example() |
|||
</syntaxhighlight> |
|||
=={{header|Objeck}}== |
|||
<syntaxhighlight lang="objeck">class Repeat { |
|||
function : Main(args : String[]) ~ Nil { |
|||
Repeat(Example() ~ Nil, 3); |
|||
} |
|||
function : Repeat(e : () ~ Nil, i : Int) ~ Nil { |
|||
while(i-- > 0) { |
|||
e(); |
|||
}; |
|||
} |
|||
function : Example() ~ Nil { |
|||
"Example"->PrintLine(); |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let repeat ~f ~n = |
||
for i = 1 to n do |
for i = 1 to n do |
||
f () |
f () |
||
Line 461: | Line 1,577: | ||
let () = |
let () = |
||
repeat ~n:4 ~f:func |
repeat ~n:4 ~f:func |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 468: | Line 1,583: | ||
This method is already defined : times. This method can be used on all runnables (functions, methods, blocks, ...). |
This method is already defined : times. This method can be used on all runnables (functions, methods, blocks, ...). |
||
< |
<syntaxhighlight lang="oforth">: hello "Hello, World!" println ; |
||
10 #hello times</ |
10 #hello times</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 484: | Line 1,599: | ||
Hello, World! |
Hello, World! |
||
</pre> |
</pre> |
||
=={{header|Ol}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
; sample function |
|||
(define (function) (display "+")) |
|||
; simple case for 80 times |
|||
(for-each (lambda (unused) (function)) (iota 80)) |
|||
(print) ; print newline |
|||
; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
|||
; detailed case for 80 times |
|||
(let loop ((fnc function) (n 80)) |
|||
(unless (zero? n) |
|||
(begin |
|||
(fnc) |
|||
(loop fnc (- n 1))))) |
|||
(print) ; print newline |
|||
; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
|||
</syntaxhighlight> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">repeat(f, n)=for(i=1,n,f()); |
||
repeat( ()->print("Hi!"), 2);</ |
repeat( ()->print("Hi!"), 2);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hi! |
<pre>Hi! |
||
Hi!</pre> |
Hi!</pre> |
||
=={{header|Pascal}}== |
|||
<syntaxhighlight lang="pascal">program Repeater; |
|||
type |
|||
TProc = procedure(I: Integer); |
|||
procedure P(I: Integer); |
|||
begin |
|||
WriteLn('Iteration ', I); |
|||
end; |
|||
procedure Iterate(P: TProc; N: Integer); |
|||
var |
|||
I: Integer; |
|||
begin |
|||
for I := 1 to N do |
|||
P(I); |
|||
end; |
|||
begin |
|||
Iterate(P, 3); |
|||
end. </syntaxhighlight> |
|||
{{out}} |
|||
<pre>Iteration 1 |
|||
Iteration 2 |
|||
Iteration 3</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Line 496: | Line 1,657: | ||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="perl">sub repeat { |
||
my ($sub, $n) = @_; |
my ($sub, $n) = @_; |
||
$sub->() for 1..$n; |
$sub->() for 1..$n; |
||
Line 505: | Line 1,666: | ||
} |
} |
||
repeat(\&example, 4);</ |
repeat(\&example, 4);</syntaxhighlight> |
||
=={{header| |
=={{header|Phix}}== |
||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #008080;">procedure</span> <span style="color: #000000;">Repeat</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #000000;">rid</span><span style="color: #0000FF;">()</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
|||
<span style="color: #008080;">procedure</span> <span style="color: #000000;">Hello</span><span style="color: #0000FF;">()</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #008000;">"Hello"</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
|||
<span style="color: #000000;">Repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">Hello</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> |
|||
<!--</syntaxhighlight>--> |
|||
=={{header|Phixmonti}}== |
|||
<lang perl6>sub repeat (&f, $n) { f() xx $n }; |
|||
<syntaxhighlight lang="phixmonti">def myFunc |
|||
"Sure looks like a function in here..." print nl |
|||
enddef |
|||
def rep /# func times -- #/ |
|||
for drop |
|||
dup exec |
|||
endfor |
|||
drop |
|||
enddef |
|||
getid myFunc 4 rep |
|||
sub example { say rand } |
|||
</syntaxhighlight> |
|||
repeat(&example, 3);</lang> |
|||
{{Output}} |
|||
<pre> |
|||
0.435249779778396 |
|||
0.647701200726486 |
|||
0.279289335968417 |
|||
</pre> |
|||
Of course, we could have just written <pre style="display:inline; padding:0.3em">example() xx 3;</pre> or even <pre style="display:inline; padding:0.3em">(say rand) xx 3;</pre> directly – the custom <code>repeat</code> subroutine is just here to satisfy the task description. |
|||
Notes on the [http://doc.perl6.org/language/operators#infix_xx <code>xx</code>] operator: |
|||
* Unlike other operators, it evaluates its left-hand-side argument lazily - that's why we can simply call <code>f()</code> there rather than passing it as a function object. |
|||
* The operator has a return value: A list consisting of the return values of the left-hand-side ''(and building lists is in fact what <code>xx</code> is usually used for)''. |
|||
General notes: |
|||
* The <code>&</code> sigil in the <code>repeat</code> subroutine signature restricts that parameter to types that implement the <code>Callable</code> role, and makes it available inside the <code>repeat</code> subroutine body as if it were a lexically scoped sub. |
|||
* The parentheses in the last line are necessary to disambiguate it as a call to our custom subroutine, rather than an attempt to use the built-in <code>repeat { ... } while ...</code> construct. |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp"># The built-in function "do" can be used to achieve our goal, |
||
# however, it has a slightly different syntax than what the |
# however, it has a slightly different syntax than what the |
||
# problem specifies. |
# problem specifies. |
||
Line 546: | Line 1,711: | ||
(do N (Fn)) ) |
(do N (Fn)) ) |
||
(dofn version 10)</ |
(dofn version 10)</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
{{trans|Python}} (Made more PowerShelly.) |
{{trans|Python}} (Made more PowerShelly.) |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function Out-Example |
function Out-Example |
||
{ |
{ |
||
Line 565: | Line 1,730: | ||
Step-Function Out-Example -Repeat 3 |
Step-Function Out-Example -Repeat 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 572: | Line 1,737: | ||
Example 3 |
Example 3 |
||
</pre> |
</pre> |
||
=={{header|Prolog}}== |
|||
<syntaxhighlight lang="prolog">repeat(_, 0). |
|||
repeat(Callable, Times) :- |
|||
succ(TimesLess1, Times), |
|||
Callable, |
|||
repeat(Callable, TimesLess1). |
|||
test :- write('Hello, World'), nl. |
|||
test(Name) :- format('Hello, ~w~n', Name).</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
?- repeat(test, 3). |
|||
Hello, World |
|||
Hello, World |
|||
Hello, World |
|||
true ; |
|||
false. |
|||
?- repeat(test('Fred'), 3). |
|||
Hello, Fred |
|||
Hello, Fred |
|||
Hello, Fred |
|||
true ; |
|||
false. |
|||
</pre> |
|||
=={{header|PureBasic}}== |
|||
<syntaxhighlight lang="purebasic">Prototype.i fun(x.i) |
|||
Procedure.i quark(z.i) |
|||
Debug "Quark "+Str(z) : ProcedureReturn z-1 |
|||
EndProcedure |
|||
Procedure rep(q.fun,n.i) |
|||
Repeat : n=q(n) : Until n=0 |
|||
EndProcedure |
|||
rep(@quark(),3)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Quark 3 |
|||
Quark 2 |
|||
Quark 1</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
<lang Python>#!/usr/bin/python |
|||
===Procedural=== |
|||
<syntaxhighlight lang="python">#!/usr/bin/python |
|||
def repeat(f,n): |
def repeat(f,n): |
||
for i in range(n): |
for i in range(n): |
||
Line 582: | Line 1,793: | ||
print("Example"); |
print("Example"); |
||
repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.</ |
repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.</syntaxhighlight> |
||
===Functional=== |
|||
Repeated function application: |
|||
{{Works with|Python|3.7}} |
|||
<syntaxhighlight lang="python">'''Application of a given function, repeated N times''' |
|||
from itertools import repeat |
|||
from functools import reduce |
|||
from inspect import getsource |
|||
# applyN :: Int -> (a -> a) -> a -> a |
|||
def applyN(n): |
|||
'''n compounding applications of the supplied |
|||
function f. Equivalent to Church numeral n. |
|||
''' |
|||
def go(f): |
|||
return lambda x: reduce( |
|||
lambda a, g: g(a), repeat(f, n), x |
|||
) |
|||
return lambda f: go(f) |
|||
# MAIN ---------------------------------------------------- |
|||
def main(): |
|||
'''Tests - compounding repetition |
|||
of function application. |
|||
''' |
|||
def f(x): |
|||
return x + 'Example\n' |
|||
def g(x): |
|||
return 2 * x |
|||
def h(x): |
|||
return 1.05 * x |
|||
print( |
|||
fTable(__doc__ + ':')( |
|||
lambda fx: '\nRepeated * 3:\n (' + ( |
|||
getsource(fst(fx)).strip() + ')(' + |
|||
repr(snd(fx)) + ')' |
|||
) |
|||
)(str)( |
|||
liftA2(applyN(3))(fst)(snd) |
|||
)([(f, '\n'), (g, 1), (h, 100)]) |
|||
) |
|||
# GENERIC ------------------------------------------------- |
|||
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c |
|||
def compose(g): |
|||
'''Right to left function composition.''' |
|||
return lambda f: lambda x: g(f(x)) |
|||
# fst :: (a, b) -> a |
|||
def fst(tpl): |
|||
'''First member of a pair.''' |
|||
return tpl[0] |
|||
# liftA2 :: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> c |
|||
def liftA2(op): |
|||
'''Lift a binary function to a composition |
|||
over two other functions. |
|||
liftA2 (*) (+ 2) (+ 3) 7 == 90 |
|||
''' |
|||
def go(f, g): |
|||
return lambda x: op( |
|||
f(x) |
|||
)(g(x)) |
|||
return lambda f: lambda g: go(f, g) |
|||
# snd :: (a, b) -> b |
|||
def snd(tpl): |
|||
'''Second member of a pair.''' |
|||
return tpl[1] |
|||
# fTable :: String -> (a -> String) -> |
|||
# (b -> String) -> (a -> b) -> [a] -> String |
|||
def fTable(s): |
|||
'''Heading -> x display function -> fx display function -> |
|||
f -> xs -> tabular string. |
|||
''' |
|||
def go(xShow, fxShow, f, xs): |
|||
ys = [xShow(x) for x in xs] |
|||
w = max(map(len, ys)) |
|||
return s + '\n' + '\n'.join(map( |
|||
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), |
|||
xs, ys |
|||
)) |
|||
return lambda xShow: lambda fxShow: lambda f: lambda xs: go( |
|||
xShow, fxShow, f, xs |
|||
) |
|||
# MAIN --- |
|||
if __name__ == '__main__': |
|||
main()</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>Application of a given function, repeated N times: |
|||
Repeated * 3: |
|||
(def f(x): |
|||
return x + 'Example\n')('\n') -> |
|||
Example |
|||
Example |
|||
Example |
|||
Repeated * 3: |
|||
(def g(x): |
|||
return 2 * x)(1) -> 8 |
|||
Repeated * 3: |
|||
(def h(x): |
|||
return 1.05 * x)(100) -> 115.7625</pre> |
|||
=={{header|Quackery}}== |
|||
This is a function which is part of the Quackery language. ''times'' performs the word or nest after it the number of times specified on the stack. The definition is reproduced here, along with the additional functionality included in the language; ''i'' counts down to zero, ''i^'' counts up from zero, ''step'' specifies the increment size from an argument on the stack (default is 1), ''conclude'' sets the iteration countdown to the final value (0) and ''refresh'' sets the iteration countdown to the initial value. ''times'' is nestable, and words such as ''witheach'' (which makes use of ''times'' to iterate over a nest) inherit its additional functionality. |
|||
The word ''rosetta-times'' is also defined here, using ''times''. It takes both the repeat number and the function as stack arguments. |
|||
<syntaxhighlight lang="quackery"> [ stack ] is times.start ( --> s ) |
|||
protect times.start |
|||
[ stack ] is times.count ( --> s ) |
|||
protect times.count |
|||
[ stack ] is times.action ( --> s ) |
|||
protect times.action |
|||
[ ]'[ times.action put |
|||
dup times.start put |
|||
[ 1 - dup -1 > while |
|||
times.count put |
|||
times.action share do |
|||
times.count take again ] |
|||
drop |
|||
times.action release |
|||
times.start release ] is times ( n --> ) |
|||
[ times.count share ] is i ( --> n ) |
|||
[ times.start share i 1+ - ] is i^ ( --> n ) |
|||
[ 0 times.count replace ] is conclude ( --> ) |
|||
[ times.start share |
|||
times.count replace ] is refresh ( --> ) |
|||
[ times.count take 1+ |
|||
swap - times.count put ] is step ( --> s ) |
|||
[ nested ' times nested |
|||
swap join do ] is rosetta-times ( n x --> )</syntaxhighlight> |
|||
{{Out}} |
|||
''rosetta-times'' demonstrated in the Quackery shell. (REPL) |
|||
<pre>/O> [ say "hello" cr ] is hi |
|||
... 5 ' hi rosetta-times |
|||
... |
|||
hello |
|||
hello |
|||
hello |
|||
hello |
|||
hello |
|||
Stack empty.</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
<syntaxhighlight lang="r"> |
|||
<lang R> |
|||
f1 <- function(...){print("coucou")} |
f1 <- function(...){print("coucou")} |
||
Line 593: | Line 1,978: | ||
f2(f1,4) |
f2(f1,4) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
The racket guide has a section called [http://docs.racket-lang.org/guide/for.html?q=iterators "Iterators and Comprehensions"], which shows that ''for'' isn't just for repeating n times! |
The racket guide has a section called [http://docs.racket-lang.org/guide/for.html?q=iterators "Iterators and Comprehensions"], which shows that ''for'' isn't just for repeating n times! |
||
< |
<syntaxhighlight lang="racket">#lang racket/base |
||
(define (repeat f n) ; the for loop is idiomatic of (although not exclusive to) racket |
(define (repeat f n) ; the for loop is idiomatic of (although not exclusive to) racket |
||
(for ((_ n)) (f))) |
(for ((_ n)) (f))) |
||
Line 609: | Line 1,994: | ||
(display "...") |
(display "...") |
||
(repeat2 (λ () (display " & over")) 5) |
(repeat2 (λ () (display " & over")) 5) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>... and over and over and over and over and over... & over & over & over & over & over</pre> |
<pre>... and over and over and over and over and over... & over & over & over & over & over</pre> |
||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
<syntaxhighlight lang="raku" line>sub repeat (&f, $n) { f() xx $n }; |
|||
sub example { say rand } |
|||
repeat(&example, 3);</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
0.435249779778396 |
|||
0.647701200726486 |
|||
0.279289335968417 |
|||
</pre> |
|||
Of course, we could have just written <pre style="display:inline; padding:0.3em">example() xx 3;</pre> or even <pre style="display:inline; padding:0.3em">(say rand) xx 3;</pre> directly – the custom <code>repeat</code> subroutine is just here to satisfy the task description. |
|||
Notes on the [http://doc.raku.org/language/operators#infix_xx <code>xx</code>] operator: |
|||
* Unlike other operators, it evaluates its left-hand-side argument lazily - that's why we can simply call <code>f()</code> there rather than passing it as a function object. |
|||
* The operator has a return value: A list consisting of the return values of the left-hand-side ''(and building lists is in fact what <code>xx</code> is usually used for)''. |
|||
General notes: |
|||
* The <code>&</code> sigil in the <code>repeat</code> subroutine signature restricts that parameter to types that implement the <code>Callable</code> role, and makes it available inside the <code>repeat</code> subroutine body as if it were a lexically scoped sub. |
|||
* The parentheses in the last line are necessary to disambiguate it as a call to our custom subroutine, rather than an attempt to use the built-in <code>repeat { ... } while ...</code> construct. |
|||
=={{header|Red}}== |
|||
<syntaxhighlight lang="rebol">Red[] |
|||
myrepeat: function [fn n] [loop n [do fn]] |
|||
myrepeat [print "hello"] 3</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
hello |
|||
hello |
|||
hello |
|||
</pre> |
|||
=={{header|Refal}}== |
|||
<syntaxhighlight lang="refal">$ENTRY Go { |
|||
= <Prout <Repeat 3 Example> Eggs And <Example>>; |
|||
} |
|||
Repeat { |
|||
0 s.F e.X = e.X; |
|||
s.N s.F e.X = <Repeat <- s.N 1> s.F <Mu s.F e.X>>; |
|||
}; |
|||
Example { |
|||
e.X = e.X Spam; |
|||
};</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Spam Spam Spam Eggs And Spam</pre> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
The procedure name (that is being repeatedly executed) isn't restricted to an ''internal'' REXX subroutine (procedure), |
The procedure name (that is being repeatedly executed) isn't restricted to an ''internal'' REXX subroutine (procedure), |
||
<br>it may be an ''external'' program (procedure) written in any language. |
<br>it may be an ''external'' program (procedure) written in any language. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program executes a named procedure a specified number of times. */ |
||
parse arg pN # . /*obtain optional arguments from the CL*/ |
parse arg pN # . /*obtain optional arguments from the CL*/ |
||
if #=='' | #=="," then #= |
if #=='' | #=="," then #= 1 /*assume once if not specified. */ |
||
if pN\=='' then call repeats pN, # /*invoke the REPEATS procedure for pN.*/ |
if pN\=='' then call repeats pN, # /*invoke the REPEATS procedure for pN.*/ |
||
exit |
exit 0 /*stick a fork in it, we're all done. */ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
repeats: procedure; parse arg x,n /*obtain the procedureName & # of times*/ |
repeats: procedure; parse arg x,n /*obtain the procedureName & # of times*/ |
||
Line 626: | Line 2,067: | ||
return /*return to invoker of the REPEATS proc*/ |
return /*return to invoker of the REPEATS proc*/ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
yabba: say 'Yabba, yabba do!'; return /*simple code; no need for PROCEDURE.*/</ |
yabba: say 'Yabba, yabba do!'; return /*simple code; no need for PROCEDURE.*/</syntaxhighlight> |
||
{{out|output|text= when using the input of: <tt> yabba 4 </tt>}} |
|||
<pre> |
<pre> |
||
Yabba, yabba do! |
Yabba, yabba do! |
||
Line 644: | Line 2,085: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
Func Main |
Func Main |
||
times(5,:test) |
times(5,:test) |
||
Line 655: | Line 2,096: | ||
Call F() |
Call F() |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
≪ → func n |
|||
≪ 1 n '''START''' func EVAL '''NEXT''' |
|||
≫ ≫ '<span style="color:blue>TIMES</span>' STO |
|||
≪ " world" "Hello" SWAP + ≫ 3 <span style="color:blue>TIMES</span> |
|||
{{out}} |
|||
<pre> |
|||
3: "Hello world" |
|||
2: "Hello world" |
|||
1: "Hello world" |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">4.times{ puts "Example" } # idiomatic way |
||
def repeat(proc,num) |
def repeat(proc,num) |
||
Line 664: | Line 2,118: | ||
end |
end |
||
repeat(->{ puts "Example" }, 4)</ |
repeat(->{ puts "Example" }, 4)</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
<lang rust>// Repeat the function f, n times. |
|||
Rust has higher-order functions. |
|||
fn repeat<F>(f: &F, n: u32) |
|||
where F: Fn() { |
|||
<syntaxhighlight lang="rust">fn repeat(f: impl FnMut(usize), n: usize) { |
|||
for _ in 0..n { |
|||
(0..n).for_each(f); |
|||
}</syntaxhighlight> |
|||
Here we define the function <code>repeat</code> which takes the function <code>Fn(usize)</code>, which is an anonymous trait constraint by the <code>impl Trait</code> syntax, in such a way that it's size can be known statically at compile time. The range iterator <code>0..n</code> is used, in combination with the <code>Iterator::for_each</code> method to consume it. |
|||
=== Closure === |
|||
It's idiomatic to use a closure. |
|||
<syntaxhighlight lang="rust">fn main() { |
|||
repeat(|x| print!("{};", x), 5); |
|||
}</syntaxhighlight> |
|||
{{out}}<pre>0;1;2;3;4;</pre> |
|||
=== Static Function === |
|||
Also possible to define a static function. |
|||
<syntaxhighlight lang="rust">fn function(x: usize) { |
|||
print!("{};", x); |
|||
} |
|||
fn main() { |
|||
repeat(function, 4); |
|||
}</syntaxhighlight> |
|||
{{out}}<pre>0;1;2;3;</pre> |
|||
=== Static Method === |
|||
Sometimes it may be convenient to call a static method. |
|||
<syntaxhighlight lang="rust">struct Foo; |
|||
impl Foo { |
|||
fn associated(x: usize) { |
|||
print!("{};", x); |
|||
} |
} |
||
} |
} |
||
fn |
fn main() { |
||
repeat(Foo::associated, 8); |
|||
}</syntaxhighlight> |
|||
{{out}}<pre>0;1;2;3;4;5;6;7;</pre> |
|||
=== Trait Method === |
|||
You can also use implemented trait-methods as a function-argument. This works because the implemented type is <code>usize</code> which is what the iterator supplied to <code>Fn(usize)</code>. |
|||
<syntaxhighlight lang="rust">trait Bar { |
|||
fn run(self); |
|||
} |
|||
impl Bar for usize { |
|||
fn run(self) { |
|||
print!("{};", self); |
|||
} |
|||
} |
} |
||
fn main() { |
fn main() { |
||
repeat(Bar::run, 6); |
|||
// Repeat a static function. |
|||
}</syntaxhighlight> |
|||
repeat(&static_fn, 4); |
|||
{{out}}<pre>0;1;2;3;4;5;</pre> |
|||
=== Mutable Closure === |
|||
println!(""); |
|||
The most interesting application would probably be a mutable closure, which requires changing the type signature from <code>Fn</code> to <code>FnMut</code>, because they are constrained by slightly different rules, but otherwise work the same. |
|||
// Repeat an anonymous closure. |
|||
repeat(&|| print!("Closure "), 5); |
|||
<syntaxhighlight lang="rust">fn repeat(f: impl FnMut(usize), n: usize) { |
|||
}</lang> |
|||
(0..n).for_each(f); |
|||
{{out}} |
|||
} |
|||
<pre>Static Static Static Static |
|||
Closure Closure Closure Closure Closure</pre> |
|||
fn main() { |
|||
let mut mult = 1; |
|||
repeat(|x| { |
|||
print!("{};", x * mult); |
|||
mult += x; |
|||
}, 5); |
|||
}</syntaxhighlight> |
|||
{{out}}<pre>0;1;4;12;28;</pre> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Line 697: | Line 2,210: | ||
# Type parameterization |
# Type parameterization |
||
# Higher order function |
# Higher order function |
||
< |
<syntaxhighlight lang="scala"> def repeat[A](n:Int)(f: => A)= ( 0 until n).foreach(_ => f) |
||
repeat(3) { println("Example") }</ |
repeat(3) { println("Example") }</syntaxhighlight> |
||
===Advanced Scala-ish === |
===Advanced Scala-ish === |
||
# Call by name |
# Call by name |
||
Line 706: | Line 2,219: | ||
# Tail recursion |
# Tail recursion |
||
# Infix notation |
# Infix notation |
||
< |
<syntaxhighlight lang="scala">object Repeat2 extends App { |
||
implicit class IntWithTimes(x: Int) { |
implicit class IntWithTimes(x: Int) { |
||
Line 721: | Line 2,234: | ||
5 times println("ha") // Not recommended infix for 5.times(println("ha")) aka dot notation |
5 times println("ha") // Not recommended infix for 5.times(println("ha")) aka dot notation |
||
}</ |
}</syntaxhighlight> |
||
===Most Scala-ish === |
===Most Scala-ish === |
||
Line 730: | Line 2,243: | ||
# Infix notation |
# Infix notation |
||
# Operator overloading |
# Operator overloading |
||
< |
<syntaxhighlight lang="scala">import scala.annotation.tailrec |
||
object Repeat3 extends App { |
object Repeat3 extends App { |
||
Line 747: | Line 2,260: | ||
print("ha") * 5 // * is the method, effective should be A.*(5) |
print("ha") * 5 // * is the method, effective should be A.*(5) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
|||
Scheme is mostly made up from expressions which return values. However some functions, such as <tt>display</tt>, return |
|||
an unspecified value. The actual value returned varies depending on the Scheme implementation itself. |
|||
<syntaxhighlight lang="scheme"> |
|||
(import (scheme base) |
|||
(scheme write)) |
|||
(define (repeat proc n) |
|||
(do ((i 0 (+ 1 i)) |
|||
(res '() (cons (proc) res))) |
|||
((= i n) res))) |
|||
;; example returning an unspecified value |
|||
(display (repeat (lambda () (display "hi\n")) 4)) (newline) |
|||
;; example returning a number |
|||
(display (repeat (lambda () (+ 1 2)) 5)) (newline) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
(Using chibi-scheme: returns #<undef> from <tt>display</tt>.) |
|||
<pre> |
|||
hi |
|||
hi |
|||
hi |
|||
hi |
|||
(#<undef> #<undef> #<undef> #<undef>) |
|||
(3 3 3 3 3) |
|||
</pre> |
|||
=={{header|Seed7}}== |
|||
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
|||
const proc: myRepeat (in integer: times, in proc: aProcedure) is func |
|||
local |
|||
var integer: n is 0; |
|||
begin |
|||
for n range 1 to times do |
|||
aProcedure; |
|||
end for; |
|||
end func; |
|||
const proc: main is func |
|||
begin |
|||
myRepeat(3, writeln("Hello!")); |
|||
end func;</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Hello! |
|||
Hello! |
|||
Hello! |
|||
</pre> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func repeat(f, n) { |
||
{ f() } * n; |
{ f() } * n; |
||
} |
} |
||
Line 758: | Line 2,327: | ||
} |
} |
||
repeat(example, 4);</ |
repeat(example, 4);</syntaxhighlight> |
||
=={{header|Standard ML}}== |
|||
<syntaxhighlight lang="sml">fun repeat (_, 0) = () |
|||
| repeat (f, n) = (f (); repeat (f, n - 1)) |
|||
fun testProcedure () = |
|||
print "test\n" |
|||
val () = repeat (testProcedure, 5)</syntaxhighlight> |
|||
=={{header|Stata}}== |
|||
<syntaxhighlight lang="stata">function repeat(f,n) { |
|||
for (i=1; i<=n; i++) (*f)() |
|||
} |
|||
function hello() { |
|||
printf("Hello\n") |
|||
} |
|||
repeat(&hello(),3)</syntaxhighlight> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func repeat(n: Int, f: () -> ()) { |
||
for _ in 0..<n { |
for _ in 0..<n { |
||
f() |
f() |
||
Line 767: | Line 2,357: | ||
} |
} |
||
repeat(4) { println("Example") }</ |
repeat(4) { println("Example") }</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
The usual way of doing a repeat would be: |
The usual way of doing a repeat would be: |
||
< |
<syntaxhighlight lang="tcl">proc repeat {command count} { |
||
for {set i 0} {$i < $count} {incr i} { |
for {set i 0} {$i < $count} {incr i} { |
||
uplevel 1 $command |
uplevel 1 $command |
||
Line 778: | Line 2,368: | ||
proc example {} {puts "This is an example"} |
proc example {} {puts "This is an example"} |
||
repeat example 4</ |
repeat example 4</syntaxhighlight> |
||
However, the <code>time</code> command can be used as long as the return value (the report on the timing information) is ignored. |
However, the <code>time</code> command can be used as long as the return value (the report on the timing information) is ignored. |
||
<lang |
<syntaxhighlight lang="tcl">time example 4</syntaxhighlight> |
||
It should be noted that the “command” can be an arbitrary script, not just a call to a procedure: |
It should be noted that the “command” can be an arbitrary script, not just a call to a procedure: |
||
< |
<syntaxhighlight lang="tcl">repeat {puts "hello world"} 3</syntaxhighlight> |
||
=={{header|uBasic/4tH}}== |
|||
<syntaxhighlight lang="text">Proc _Repeat (_HelloWorld, 5) : End |
|||
_Repeat Param (2) : Local (1) : For c@ = 1 To b@ : Proc a@ : Next : Return |
|||
_HelloWorld Print "Hello world!" : Return</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
Hello world! |
|||
Hello world! |
|||
Hello world! |
|||
Hello world! |
|||
Hello world! |
|||
0 OK, 0:35 |
|||
</pre> |
|||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa">def repeat (function f, int n) |
||
for (set n n) (> n 0) (dec n) |
for (set n n) (> n 0) (dec n) |
||
f |
f |
||
Line 796: | Line 2,402: | ||
# outputs "Hello! " 5 times |
# outputs "Hello! " 5 times |
||
repeat procedure 5</ |
repeat procedure 5</syntaxhighlight> |
||
=={{header|VBA}}== |
|||
{{trans|Phix}}<syntaxhighlight lang="vb">Private Sub Repeat(rid As String, n As Integer) |
|||
For i = 1 To n |
|||
Application.Run rid |
|||
Next i |
|||
End Sub |
|||
Private Sub Hello() |
|||
Debug.Print "Hello" |
|||
End Sub |
|||
Public Sub main() |
|||
Repeat "Hello", 5 |
|||
End Sub</syntaxhighlight> |
|||
=={{header|Verilog}}== |
|||
<syntaxhighlight lang="verilog">module main; |
|||
initial begin |
|||
repeat(5) begin |
|||
$display("Inside loop"); |
|||
end |
|||
$display("Loop Ended"); |
|||
end |
|||
endmodule</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Inside loop |
|||
Inside loop |
|||
Inside loop |
|||
Inside loop |
|||
Inside loop |
|||
Loop Ended</pre> |
|||
=={{header|Visual Basic .NET}}== |
|||
{{trans|C#}} |
|||
<syntaxhighlight lang="vbnet">Module Module1 |
|||
Sub Repeat(count As Integer, fn As Action(Of Integer)) |
|||
If IsNothing(fn) Then |
|||
Throw New ArgumentNullException("fn") |
|||
End If |
|||
For i = 1 To count |
|||
fn.Invoke(i) |
|||
Next |
|||
End Sub |
|||
Sub Main() |
|||
Repeat(3, Sub(x) Console.WriteLine("Example {0}", x)) |
|||
End Sub |
|||
End Module</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Example 1 |
|||
Example 2 |
|||
Example 3</pre> |
|||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="v (vlang)">fn repeat(n int, f fn()) { |
|||
for _ in 0.. n { |
|||
f() |
|||
} |
|||
} |
|||
fn func() { |
|||
println("Example") |
|||
} |
|||
fn main() { |
|||
repeat(4, func) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Example |
|||
Example |
|||
Example |
|||
Example |
|||
</pre> |
|||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">var f = Fn.new { |g, n| |
|||
for (i in 1..n) g.call(n) |
|||
} |
|||
var g = Fn.new { |k| |
|||
for (i in 1..k) System.write("%(i) ") |
|||
System.print() |
|||
} |
|||
f.call(g, 5)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 2 3 4 5 |
|||
1 2 3 4 5 |
|||
1 2 3 4 5 |
|||
1 2 3 4 5 |
|||
1 2 3 4 5 |
|||
</pre> |
|||
=={{header|XBS}}== |
|||
XBS has a built-in repeat keyword. |
|||
<syntaxhighlight lang="xbs">func rep(callback:function,amount:number,*args:array=[]):null{ |
|||
repeat amount { |
|||
callback(*args); |
|||
} |
|||
} |
|||
rep(func(a,b,c){ |
|||
log(a+b+c); |
|||
},3,1,2,3);</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
6 |
|||
6 |
|||
6 |
|||
</pre> |
|||
=={{header|XLISP}}== |
|||
<syntaxhighlight lang="lisp">(defun repeat (f n) |
|||
(f) |
|||
(if (> n 1) |
|||
(repeat f (- n 1)) ) ) |
|||
;; an example to test it: |
|||
(repeat (lambda () (print '(hello rosetta code))) 5)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(HELLO ROSETTA CODE) |
|||
(HELLO ROSETTA CODE) |
|||
(HELLO ROSETTA CODE) |
|||
(HELLO ROSETTA CODE) |
|||
(HELLO ROSETTA CODE)</pre> |
|||
=={{header|Yabasic}}== |
|||
{{trans|Lua}} |
|||
<syntaxhighlight lang="yabasic">sub myFunc () |
|||
print "Sure looks like a function in here..." |
|||
end sub |
|||
sub rep (func$, times) |
|||
for count = 1 to times |
|||
execute(func$) |
|||
next |
|||
end sub |
|||
rep("myFunc", 4)</syntaxhighlight> |
|||
=={{header|Z80 Assembly}}== |
|||
=== Return Trick === |
|||
This technique is called the "Return Trick", it's efficient but makes the program more difficult to read. It works on the principle that the processor's RET command assumes the return address is the top item of the stack. The programmer can abuse this to "return" to a section of code that has never actually been executed. This is essentially just another form of the computed goto. Most processors that use the stack to store return addresses can use this technique, though the method of doing it depends on the processor itself. |
|||
<syntaxhighlight lang="z80"> |
|||
ld b,&05 ;load the decrement value into b |
|||
ld hl,myFunc ;load the address of "myFunc" into HL |
|||
call repeatProcedure |
|||
forever: |
|||
jp forever ;trap the program counter here |
|||
repeatProcedure: ;input: b = times to repeat, hl = which procedure to repeat |
|||
call trampoline |
|||
; the "ret" in myFunc will bring you here |
|||
djnz repeatProcedure |
|||
ret ;exit "repeatProcedure" and proceed to "forever" |
|||
trampoline: |
|||
push hl |
|||
ret |
|||
;this is effectively a call to whatever is in HL, in this case "myFunc." The "ret" at the end of myFunc will return us to |
|||
;just after the line "call trampoline" |
|||
myFunc: ;this doesn't do anything useful but that's not the point |
|||
push hl ;not needed for this routine but if it altered HL we would need this so that we come back here next time we loop |
|||
or a |
|||
pop hl |
|||
ret |
|||
</syntaxhighlight> |
|||
=== Indirect Jump === |
|||
Same as above but uses an indirect jump to the address in HL. |
|||
<syntaxhighlight lang="z80">trampoline: |
|||
jp (hl) ;despite the parentheses this does NOT dereference HL, it merely acts as "LD PC,HL".</syntaxhighlight> |
|||
===Using self-modifying code=== |
|||
This method assumes the routine doesn't use the B register, or restores it before returning. Also, the actual "wrapper" used to repeat the passed function must be in RAM so that its instructions can be modified at runtime. |
|||
<syntaxhighlight lang="z80"> |
|||
LD HL,myFunc |
|||
LD (repeatproc+1),HL |
|||
LD B,5 ;repeat count |
|||
CALL repeatProc |
|||
;somewhere far away from here: |
|||
repeatProc: |
|||
call &0000 ;gets overwritten with the address of MyFunc |
|||
djnz repeatProc |
|||
ret</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn repeat(f,n){ do(n){ f() } } |
||
repeat("ho ".print,3);</ |
repeat("ho ".print,3);</syntaxhighlight> |
||
{{out}}<pre>ho ho ho </pre> |
{{out}}<pre>ho ho ho </pre> |
Latest revision as of 16:10, 7 May 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
11l
F repeat(f, n)
L 1..n
f()
F procedure()
print(‘Example’)
repeat(procedure, 3)
- Output:
Example Example Example
6502 Assembly
Using a trampoline
This routine is a bit messy, and assumes the called routine doesn't clobber the zero-page memory used to maintain it. This can be modified to push/pop those values before/after the routine is executed.
macro RepeatProc,addr,count ;VASM macro syntax
; input:
; addr = the label of the routine you wish to call repeatedly
; count = how many times you want to DO the procedure. 1 = once, 2 = twice, 3 = three times, etc. Enter "0" for 256 times.
lda #<\addr
sta z_L ;a label for a zero-page memory address
lda #>\addr
sta z_H ;a label for the zero-page memory address immediately after z_L
lda \count
jsr doRepeatProc
endm
doRepeatProc:
sta z_C ;another zero-page memory location
loop_RepeatProc:
jsr Trampoline_RepeatProc
dec z_C
lda z_C
bne loop_RepeatProc
rts
Trampoline_RepeatProc:
db $6c,z_L,$00
;when executed, becomes an indirect JMP to the address stored at z_L and z_H. Some assemblers will let you type
;JMP (z_L) and it will automatically replace it with the above during the assembly process.
;This causes an indirect JMP to the routine. Its RTS will return execution to just after the "JSR Trampoline_RepeatProc"
;and flow into the loop overhead.
Once the macro and the underlying subroutine are created, this is very simple to use:
RepeatProc foo,#20 ;perform the subroutine "foo" twenty times.
Using self-modifying code
This version requires that your "wrapper" executes in RAM, so that it can be modified. For this to work, it is assumed that the routine you're using doesn't clobber Y, or require that its parameters are passed in by A or X (so admittedly this method is a bit limited, but if you use the zero page to hold the parameters you can set them up prior to calling the wrapper itself.
RepeatProc:
;input: low byte of desired function address in A
; high byte of desired function address in X
; repeat count in Y
STA smc_repeatproc+1
STX smc_repeatproc+2
smc_repeatproc:
jsr $0000 ;this is modified by the STA and STX above.
dey
bne smc_repeatproc
rts
68000 Assembly
This example code prints an exclamation point to the screen 4 times. It is assumed that the functions called do not clobber A5 or D7, as doing so would cause undefined behavior (read: a crash or a program counter "escape.")
lea foo,a5 ;function to execute
move.w #4-1,d7 ;times to repeat
jsr Repeater
jmp * ;halt the CPU, we're done
repeater:
jsr repeaterhelper ;this also need to be a call, so that the RTS of the desired procedure
;returns us to the loop rather than the line after "jsr Repeater".
DBRA D7,repeater
rts
repeaterhelper:
jmp (a5) ;keep in mind, this is NOT a dereference, it simply sets the program counter equal to A5.
;A bit misleading if you ask me.
foo:
MOVE.B #'!',D0
JSR PrintChar
rts
- Output:
!!!!
Action!
DEFINE PTR="CARD"
PROC OutputText(CHAR ARRAY s)
PrintE(s)
RETURN
PROC Procedure=*(CHAR ARRAY s)
DEFINE JSR="$20"
DEFINE RTS="$60"
[JSR $00 $00 ;JSR to address set by SetProcedure
RTS]
PROC SetProcedure(PTR p)
PTR addr
addr=Procedure+1 ;location of address of JSR
PokeC(addr,p)
RETURN
PROC Repeat(PTR procFun CHAR ARRAY s BYTE n)
BYTE i
SetProcedure(procFun)
FOR i=1 TO n
DO
Procedure(s)
OD
RETURN
PROC Main()
Repeat(OutputText,"Action!",5)
RETURN
- Output:
Screenshot from Atari 8-bit computer
Action! Action! Action! Action! Action!
Ada
with Ada.Text_IO;
procedure Repeat_Example is
procedure Repeat(P: access Procedure; Reps: Natural) is
begin
for I in 1 .. Reps loop
P.all; -- P points to a procedure, and P.all actually calls that procedure
end loop;
end Repeat;
procedure Hello is
begin
Ada.Text_IO.Put("Hello! ");
end Hello;
begin
Repeat(Hello'Access, 3); -- Hello'Access points to the procedure Hello
end Repeat_Example;
Output:
Hello! Hello! Hello!
ALGOL 68
# operator that executes a procedure the specified number of times #
OP REPEAT = ( INT count, PROC VOID routine )VOID:
TO count DO routine OD;
# make REPEAT a low priority operater #
PRIO REPEAT = 1;
# can also create variant that passes the iteration count as a parameter #
OP REPEAT = ( INT count, PROC( INT )VOID routine )VOID:
FOR iteration TO count DO routine( iteration ) OD;
main: (
# PROC to test the REPEAT operator with #
PROC say something = VOID: print( ( "something", newline ) );
3 REPEAT say something;
# PROC to test the variant #
PROC show squares = ( INT n )VOID: print( ( n, n * n, newline ) );
3 REPEAT show squares
)
Output:
something something something +1 +1 +2 +4 +3 +9
ALGOL W
As well as the names of procedures, Algol W allows statements to be passed as parameters where a procedure is expected.
begin
% executes the procedure routine the specified number of times %
procedure repeat ( integer value count; procedure routine ) ;
for i := 1 until count do routine;
begin
integer x;
% print "hello" three times %
repeat( 3, write( "hello" ) );
% print the first 10 squares %
write();
x := 1;
repeat( 10
, begin
writeon( i_w := s_w := 1, x * x );
x := x + 1
end
)
end
end.
- Output:
hello hello hello 1 4 9 16 25 36 49 64 81 100
AppleScript
-- applyN :: Int -> (a -> a) -> a -> a
on applyN(n, f, x)
script go
on |λ|(a, g)
|λ|(a) of mReturn(g)
end |λ|
end script
foldl(go, x, replicate(n, f))
end applyN
-------- SAMPLE FUNCTIONS FOR REPEATED APPLICATION --------
on double(x)
2 * x
end double
on plusArrow(s)
s & " -> "
end plusArrow
on squareRoot(n)
n ^ 0.5
end squareRoot
-------------------------- TESTS --------------------------
on run
log applyN(10, double, 1)
--> 1024
log applyN(5, plusArrow, "")
--> " -> -> -> -> -> "
log applyN(3, squareRoot, 65536)
--> 4.0
end run
-------------------- GENERIC FUNCTIONS --------------------
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if 1 > n then return out
set dbl to {a}
repeat while (1 < n)
if 0 < (n mod 2) then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
- Output:
(*1024*) (* -> -> -> -> -> *) (*4.0*)
Applesoft BASIC
https://web.archive.org/web/20190202165511/http://hoop-la.ca/apple2/2016/winterwarmup/#repeat.bas
100 FOR I = 768 TO 794
110 READ B: POKE I,B: NEXT
120 DATA165,185,72,165,184,72
130 DATA165,118,72,165,117,72
140 DATA169,176,72,32,123,221
150 DATA32,82,231,32,65,217
160 DATA76,210,215
170 POKE 1014,0: POKE 1015,3
200 LET P = 400:N = 4
210 GOSUB 300"REPEAT P N
220 END
300 IF N < = 0 THEN RETURN
310 LET N = N - 1
320 & P
330 GOTO 300
400 PRINT "EXAMPLE"
410 RETURN
Arturo
print "---------------------------"
print "As a loop"
print "---------------------------"
loop 4 'x ->
print "Example 1"
repeatFunc: function [f,times][
loop times 'x ->
do f
]
print "---------------------------"
print "With a block param"
print "---------------------------"
repeatFunc [print "Example 2"] 4
repeatFunc: function [f,times][
loop times 'x ->
f
]
print "---------------------------"
print "With a function param"
print "---------------------------"
repeatFunc $[][print "Example 3"] 4
- Output:
--------------------------- As a loop --------------------------- Example 1 Example 1 Example 1 Example 1 --------------------------- With a block param --------------------------- Example 2 Example 2 Example 2 Example 2 --------------------------- With a function param --------------------------- Example 3 Example 3 Example 3 Example 3
AutoHotkey
repeat("fMsgBox",3)
return
repeat(f, n){
loop % n
%f%()
}
fMsgBox(){
MsgBox hello
}
AWK
# syntax: GAWK -f REPEAT.AWK
BEGIN {
for (i=0; i<=3; i++) {
f = (i % 2 == 0) ? "even" : "odd"
@f(i) # indirect function call
}
exit(0)
}
function even(n, i) {
for (i=1; i<=n; i++) {
printf("inside even %d\n",n)
}
}
function odd(n, i) {
for (i=1; i<=n; i++) {
printf("inside odd %d\n",n)
}
}
output:
inside odd 1 inside even 2 inside even 2 inside odd 3 inside odd 3 inside odd 3
BASIC
BASIC256
subroutine proc()
print " Inside loop"
end subroutine
subroutine repeat(func, times)
for i = 1 to times
call proc()
next
end subroutine
call repeat("proc", 5)
print "Loop Ended
- Output:
Inside loop Inside loop Inside loop Inside loop Inside loop Loop Ended
Chipmunk Basic
10 sub proc()
20 print " Inside loop"
30 end sub
40 sub repeat(func$,times)
50 for i = 1 to times
60 proc()
70 next i
80 end sub
90 repeat("proc",5)
100 print "Loop Ended"
110 end
- Output:
Same as BASIC256 entry.
GW-BASIC
100 let f$ = "proc"
110 let c = 5
120 gosub 170
130 print "Loop Ended"
140 goto 220
150 print " Inside loop"
160 return
170 rem repeat(f$,c)
180 for i = 1 to c
190 gosub 150
200 next i
210 return
220 end
- Output:
Same as BASIC256 entry.
Minimal BASIC
The GW-BASIC solution works without any changes.
MSX Basic
The GW-BASIC solution works without any changes.
QBasic
DECLARE SUB rep (func AS STRING, c AS INTEGER)
DECLARE SUB proc ()
CALL rep("proc", 5)
PRINT "Loop Ended"
SUB proc
PRINT " Inside loop"
END SUB
SUB rep (func AS STRING, c AS INTEGER)
FOR i = 1 TO c
proc
NEXT
END SUB
- Output:
Same as BASIC256 entry.
Quite BASIC
The GW-BASIC solution works without any changes.
True BASIC
SUB proc
PRINT " Inside loop"
END SUB
SUB rep (func$, c)
FOR i = 1 to c
CALL proc
NEXT i
END SUB
CALL rep ("proc", 5)
PRINT "Loop Ended"
END
- Output:
Same as BASIC256 entry.
XBasic
PROGRAM "Repeat"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
DECLARE FUNCTION Proc ()
DECLARE FUNCTION Repe (func$, c)
FUNCTION Entry ()
Repe ("proc", 5)
PRINT "Loop Ended"
END FUNCTION
FUNCTION Proc ()
PRINT " Inside loop"
END FUNCTION
FUNCTION Repe (func$, c)
FOR i = 1 TO c
Proc ()
NEXT i
END FUNCTION
END PROGRAM
- Output:
Same as BASIC256 entry.
Batch File
@echo off
:_main
setlocal
call:_func1 _func2 3
pause>nul
exit/b
:_func1
setlocal enabledelayedexpansion
for /l %%i in (1,1,%2) do call:%1
exit /b
:_func2
setlocal
echo _func2 has been executed
exit /b
BQN
BQN has a builtin called Repeat which fulfills the criteria for the challenge(and allows multiple iteration counts), hence there is a recursive implementation of repeat added in as well.
•Show {2+𝕩}⍟3 1
_repeat_ ← {(𝕘>0)◶⊢‿(𝔽_𝕣_(𝕘-1)𝔽)𝕩}
•Show {2+𝕩} _repeat_ 3 1
7
7
C
#include <stdio.h>
void repeat(void (*f)(void), unsigned int n) {
while (n-->0)
(*f)(); //or just f()
}
void example() {
printf("Example\n");
}
int main(int argc, char *argv[]) {
repeat(example, 4);
return 0;
}
C#
using System;
namespace Repeat {
class Program {
static void Repeat(int count, Action<int> fn) {
if (null == fn) {
throw new ArgumentNullException("fn");
}
for (int i = 0; i < count; i++) {
fn.Invoke(i + 1);
}
}
static void Main(string[] args) {
Repeat(3, x => Console.WriteLine("Example {0}", x));
}
}
}
- Output:
Example 1 Example 2 Example 3
C++
template <typename Function>
void repeat(Function f, unsigned int n) {
for(unsigned int i=n; 0<i; i--)
f();
}
usage:
#include <iostream>
void example() {
std::cout << "Example\n";
}
repeat(example, 4);
repeat([]{std::cout << "Example\n";}, 4);
Chapel
The most basic form, with generics.
config const n = 5;
proc example()
{
writeln("example");
}
proc repeat(func, n)
{
for i in 0..#n do func();
}
repeat(example, n);
With argument type hinting.
config const n = 5;
proc example()
{
writeln("example");
}
proc repeat(func : proc(), n : uint)
{
for i in 0..#n do func();
}
repeat(example, n);
Example of passing function which takes arguments. Chapel does not allow functions with generic arguments to be passed. First-class functions are still in development: https://chapel-lang.org/docs/technotes/firstClassProcedures.html
config const n = 5;
proc example(x : uint)
{
writeln("example ", x);
}
proc repeat(func : proc(x : uint), n : uint)
{
for i in 0..#n do func(i);
}
repeat(example, n);
Clojure
(defn repeat-function [f n]
(dotimes [i n] (f)))
- Output:
user=> (repeat-function #(println "bork") 3) bork bork bork
Common Lisp
(defun repeat (f n)
(dotimes (i n) (funcall f)))
(repeat (lambda () (format T "Example~%")) 5)
Cowgol
include "cowgol.coh";
# Only functions that implement an interface can be passed around
# The interface is a type and must be defined before it is used
# This defines an interface for a function that takes no arguments
interface Fn();
# This function repeats a function that implements Fn
sub Repeat(f: Fn, n: uint32) is
while n != 0 loop
f();
n := n - 1;
end loop;
end sub;
# Here is a function
sub Foo implements Fn is
print("foo ");
end sub;
# Prints "foo foo foo foo"
Repeat(Foo, 4);
print_nl();
D
void repeat(void function() fun, in uint times) {
foreach (immutable _; 0 .. times)
fun();
}
void procedure() {
import std.stdio;
"Example".writeln;
}
void main() {
repeat(&procedure, 3);
}
- Output:
Example Example Example
Delphi
program Repeater;
{$APPTYPE CONSOLE}
{$R *.res}
type
TSimpleProc = procedure; // Can also define types for procedures (& functions) which
// require params.
procedure Once;
begin
writeln('Hello World');
end;
procedure Iterate(proc : TSimpleProc; Iterations : integer);
var
i : integer;
begin
for i := 1 to Iterations do
proc;
end;
begin
Iterate(Once, 3);
readln;
end.
Alternative
program Repeater;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
procedure Iterate(proc: TProc; Iterations: integer);
var
i: integer;
begin
for i := 1 to Iterations do
proc;
end;
begin
Iterate(
procedure
begin
writeln('Hello World');
end, 3);
readln;
end.
- Output:
Hello World Hello World Hello World
EchoLisp
(define (repeat f n) (for ((i n)) (f)))
(repeat (lambda () (write (random 1000))) 5)
→ 287 798 930 989 794
;; Remark
;; It is also possible to iterate a function : f(f(f(f( ..(f x)))))
(define cos10 (iterate cos 10)
(define cos100 (iterate cos10 10))
(cos100 0.6)
→ 0.7390851332151605
(cos 0.7390851332151605)
→ 0.7390851332151608 ;; fixed point found
F#
open System
let Repeat c f =
for _ in 1 .. c do
f()
let Hello _ =
printfn "Hello world"
[<EntryPoint>]
let main _ =
Repeat 3 Hello
0 // return an integer exit code
Factor
Factor comes with the times word which does exactly this. For example,
3 [ "Hello!" print ] times
- Output:
Hello! Hello! Hello!
The implementation of times:
: times ( ... n quot: ( ... -- ... ) -- ... )
[ drop ] prepose each-integer ; inline
Fe
(= repeat (mac (i n . body)
(list 'do
(list 'let i 0)
(list 'while (list '< i n)
(list '= i (list '+ i 1))
(cons 'do body)))))
; print multiplication table
(repeat i 10
(repeat j 10
(print i "x" j "=" (* i j)))
(print))
Forth
: times ( xt n -- )
0 ?do dup execute loop drop ;
Or, taking care to keep the data stack clean for the XT's use, as is often desired:
: times { xt n -- }
n 0 ?do xt execute loop ;
Or as a novel control structure, which is not demanded by this task but which is just as idiomatic in Forth as the XT-consuming alternatives above:
: times[ ]] 0 ?do [[ ; immediate compile-only
: ]times postpone loop ; immediate compile-only
Usage:
[: cr ." Hello" ;] 3 times
: 3-byes ( -- ) 3 times[ cr ." Bye" ]times ;
3-byes
- Output:
HelloHello Hello Bye Bye
Bye
FreeBASIC
' FB 1.05.0 Win64
Sub proc()
Print " proc called"
End Sub
Sub repeat(s As Sub, n As UInteger)
For i As Integer = 1 To n
Print Using "##"; i;
s()
Next
End Sub
repeat(@proc, 5)
Print
Print "Press any key to quit"
Sleep
- Output:
1 proc called 2 proc called 3 proc called 4 proc called 5 proc called
FutureBasic
include "NSLog.incl"
void local fn Example( value as long )
NSLog(@"Example %ld",value)
end fn
void local fn DoIt( fnAddress as ptr, count as long )
def fn Repeat( j as long ) using fnAddress
long i
for i = 1 to count
fn Repeat( i )
next
end fn
fn DoIt( @fn Example, 3 )
HandleEvents
- Output:
Example 1 Example 2 Example 3
Gambas
Note: Gambas (3.14.0) cannot perform this task as specified, as it does not have delegates, and pointers do not seem to work with procedures. What does work is using Object.Call, which is intended for executing procedures from external libraries. However the accepting procedure must refer to the object containing the procedure, and refer to the procedure by a String name. In this case, the current module/class reference (Me) is used, but the String name must be passed. This arrangement will only work within the same module/class. It may be possible to pass the parent reference to a method (taking 3 parameters) in another class if the named procedure is Public. The empty array ([]) in Object.Call represent a procedure without parameters, which are not an explicit requirement for this Task, but might require another parameter to the accepting procedure.
Public Sub Main()
RepeatIt("RepeatableOne", 2)
RepeatIt("RepeatableTwo", 3)
End
'Cannot pass procedure pointer in Gambas; must pass procedure name and use Object.Call()
Public Sub RepeatIt(sDelegateName As String, iCount As Integer)
For iCounter As Integer = 1 To iCount
Object.Call(Me, sDelegateName, [])
Next
End
Public Sub RepeatableOne()
Print "RepeatableOne"
End
Public Sub RepeatableTwo()
Print "RepeatableTwo"
End
Output:
RepeatableOne RepeatableOne RepeatableTwo RepeatableTwo RepeatableTwo
Go
package main
import "fmt"
func repeat(n int, f func()) {
for i := 0; i < n; i++ {
f()
}
}
func fn() {
fmt.Println("Example")
}
func main() {
repeat(4, fn)
}
Haskell
Such a function already exists
import Control.Monad (replicateM_)
sampleFunction :: IO ()
sampleFunction = putStrLn "a"
main = replicateM_ 5 sampleFunction
And if the requirement is for something like a Church numeral, compounding the application of a given function n times (rather than repeating the same IO event n times) then we could also write something like applyN below:
applyN :: Int -> (a -> a) -> a -> a
applyN n f = foldr (.) id (replicate n f)
main :: IO ()
main = print $ applyN 10 (\x -> 2 * x) 1
- Output:
1024
Isabelle
Isabelle does not have procedures with side effects. So we cannot do things such as printing a string to stdout. Isabelle only has pure mathematical functions.
theory Scratch
imports Main
begin
text‹
Given the function we want to execute multiple times is of
type \<^typ>‹unit ⇒ unit›.
›
fun pure_repeat :: "(unit ⇒ unit) ⇒ nat ⇒ unit" where
"pure_repeat _ 0 = ()"
| "pure_repeat f (Suc n) = f (pure_repeat f n)"
text‹
Functions are pure in Isabelle. They don't have side effects.
This means, the \<^const>‹pure_repeat› we implemented is always equal
to \<^term>‹() :: unit›, independent of the function \<^typ>‹unit ⇒ unit›
or \<^typ>‹nat›.
Technically, functions are not even "executed", but only evaluated.
›
lemma "pure_repeat f n = ()" by simp
text‹
But we can repeat a value of \<^typ>‹'a› \<^term>‹n› times and return the result
in a list of length \<^term>‹n›
›
fun repeat :: "'a ⇒ nat ⇒ 'a list" where
"repeat _ 0 = []"
| "repeat f (Suc n) = f # (repeat f n)"
lemma "repeat ''Hello'' 4 = [''Hello'', ''Hello'', ''Hello'', ''Hello'']"
by code_simp
lemma "length (repeat a n) = n" by(induction n) simp+
text‹
Technically, \<^typ>‹'a› is not a function. We can wrap it in a dummy function
which takes a \<^typ>‹unit› as first argument. This gives a function of type
\<^typ>‹unit ⇒ 'a›.
›
fun fun_repeat :: "(unit ⇒ 'a) ⇒ nat ⇒ 'a list" where
"fun_repeat _ 0 = []"
| "fun_repeat f (Suc n) = (f ()) # (fun_repeat f n)"
lemma "fun_repeat (λ_. ''Hello'') 4 =
[''Hello'', ''Hello'', ''Hello'', ''Hello'']"
by code_simp
text‹
Yet, \<^const>‹fun_repeat› with the dummy function \<^typ>‹unit ⇒ 'a› is
equivalent to \<^const>‹repeat› with the value \<^typ>‹'a› directly.
›
lemma "fun_repeat (λ_. a) n = repeat a n" by(induction n) simp+
end
J
NB. ^: (J's power conjunction) repeatedly evaluates a verb.
NB. Appending to a vector the sum of the most recent
NB. 2 items can generate the Fibonacci sequence.
(, [: +/ _2&{.) (^:4) 0 1
0 1 1 2 3 5
NB. Repeat an infinite number of times
NB. computes the stable point at convergence
cosine =: 2&o.
cosine (^:_ ) 2 NB. 2 is the initial value
0.739085
cosine 0.739085 NB. demonstrate the stable point x==Cos(x)
0.739085
cosine^:(<_) 2 NB. show the convergence
2 _0.416147 0.914653 0.610065 0.819611 0.682506 0.775995 0.713725 0.755929 0.727635 0.74675 0.733901 0.742568 0.736735 0.740666 0.738019 0.739803 0.738602 0.739411 0.738866 0.739233 0.738986 0.739152 0.73904 0.739116 0.739065 0.739099 0.739076 0.739091 0.7...
# cosine^:(<_) 2 NB. iteration tallyft
78
f =: 3 :'smoutput ''hi'''
f''
hi
NB. pass verbs via a gerund
repeat =: dyad def 'for_i. i.y do. (x`:0)0 end. EMPTY'
(f`'')repeat 4
hi
hi
hi
hi
NB. pass a verb directly to an adverb
Repeat =: adverb def 'for_i. i.y do. u 0 end. EMPTY'
f Repeat 4
hi
hi
hi
hi
Java
There are two ways to achieve this, one way is through reflection.
import java.lang.reflect.Method;
public class Program {
public static void main(String[] args) throws ReflectiveOperationException {
Method method = Program.class.getMethod("printRosettaCode");
repeat(method, 5);
}
public static void printRosettaCode() {
System.out.println("Rosetta Code");
}
public static void repeat(Method method, int count) throws ReflectiveOperationException {
while (count-- > 0)
method.invoke(null);
}
}
Rosetta Code Rosetta Code Rosetta Code Rosetta Code Rosetta Code
Or
import java.util.function.Consumer;
import java.util.stream.IntStream;
public class Repeat {
public static void main(String[] args) {
repeat(3, (x) -> System.out.println("Example " + x));
}
static void repeat (int n, Consumer<Integer> fun) {
IntStream.range(0, n).forEach(i -> fun.accept(i + 1));
}
}
Output:
Example 1 Example 2 Example 3
jq
We first define "repeat" naively but in accordance with the task specification; we then define an optimized version that illustrates a general technique for taking advantage of jq's support for tail-call optimization (TCO).
Since jq is a purely functional language, repeat(f; n) is unlikely to be very useful so we define a similar filter, repeatedly(f; n), which generates n+1 terms: . (the input), f, f|f, ... ; that is, using conventional functional notation, it generates: x, f(x), f(f(x)), ...
Unoptimized version:
def unoptimized_repeat(f; n):
if n <= 0 then empty
else f, repeat(f; n-1)
end;
Optimized for TCO:
def repeat(f; n):
# state: [count, in]
def r:
if .[0] >= n then empty else (.[1] | f), (.[0] += 1 | r) end;
[0, .] | r;
Variant:
# If n is a non-negative integer,
# then emit a stream of (n + 1) terms: ., f, f|f, f|f|f, ...
def repeatedly(f; n):
# state: [count, in]
def r:
if .[0] < 0 then empty
else .[1], ([.[0] - 1, (.[1] | f)] | r)
end;
[n, .] | r;
Examples:
0 | [ repeat(.+1; 3) ]
produces: [1,1,1]
0 | repeatedly(.+1; 3)
produces:
0 1 2 3
Julia
function sayHi()
println("Hi")
end
function rep(f, n)
for i = 1:n f() end
end
rep(sayHi, 3)
- Output:
Hi Hi Hi
Kotlin
// version 1.0.6
fun repeat(n: Int, f: () -> Unit) {
for (i in 1..n) {
f()
println(i)
}
}
fun main(args: Array<String>) {
repeat(5) { print("Example ") }
}
- Output:
Example 1 Example 2 Example 3 Example 4 Example 5
Lean
Lean 3.4.2
def repeat : ℕ → (ℕ → string) → string
| 0 f := "done"
| (n + 1) f := (f n) ++ (repeat n f)
#eval repeat 5 $ λ b : ℕ , "me "
- Output:
"me me me me me done"
Lean 4
def repeatf (f : Nat -> String) (n : Nat) : String :=
match n with
| 0 => "."
| (k + 1) => (f k) ++ (repeatf f k)
def example1 : String :=
repeatf (fun (x : Nat) => toString (x) ++ " ") (10)
#eval example1
- Output:
"9 8 7 6 5 4 3 2 1 0 ."
LiveCode
rep "answer",3
command rep x,n
repeat n times
do merge("[[x]] [[n]]")
end repeat
end rep
Lua
No particular magic required as Lua allows functions to be passed as arguments.
function myFunc ()
print("Sure looks like a function in here...")
end
function rep (func, times)
for count = 1, times do
func()
end
end
rep(myFunc, 4)
- Output:
Sure looks like a function in here... Sure looks like a function in here... Sure looks like a function in here... Sure looks like a function in here...
Mastermind
Functions are in-lined at compile time in Mastermind, meaning the "repeat" function cannot accept another procedure as an argument. This is due to limitations of the compilation target, which is Brainf***. Dynamically calling functions would require creating a function runtime.
def do_something<number> {
output "Letter: ";
output 'a' + number;
output '\n';
}
def repeat<times> {
let i = 0;
drain times into i {
do_something<i>;
}
}
let repetitions = 8;
repeat<repetitions>;
- Output:
Letter: a Letter: b Letter: c Letter: d Letter: e Letter: f Letter: g Letter: h
Mathematica/Wolfram Language
Note that anything of this form is not considered good practice.
repeat[f_, n_] := Do[f[], {n}];
repeat[Print["Hello, world!"] &, 5];
- Output:
Hello, world! Hello, world! Hello, world! Hello, world! Hello, world!
min
This operator already exists in min and is called times
.
("Hello" puts!) 3 times
- Output:
Hello Hello Hello
MiniScript
sayHi = function()
print "Hi!"
end function
rep = function(f, n)
for i in range(1, n)
f
end for
end function
rep @sayHi, 3
- Output:
Hi! Hi! Hi!
МК-61/52
1 П4
3 ^ 1 6 ПП 09 С/П
П7 <-> П0 КПП7 L0 12 В/О
ИП4 С/П КИП4 В/О
Modula-2
MODULE Repeat;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE F = PROCEDURE;
PROCEDURE Repeat(fun : F; c : INTEGER);
VAR i : INTEGER;
BEGIN
FOR i:=1 TO c DO
fun
END
END Repeat;
PROCEDURE Print;
BEGIN
WriteString("Hello");
WriteLn
END Print;
BEGIN
Repeat(Print, 3);
ReadChar
END Repeat.
Nanoquery
def repeat(f,n)
for i in range(1, n)
f()
end
end
def procedure()
println "Example"
end
repeat(procedure, 3)
Nim
proc example =
echo "Example"
# Ordinary procedure
proc repeatProc(fn: proc, n: int) =
for x in 0..<n:
fn()
repeatProc(example, 4)
# Template (code substitution), simplest form of metaprogramming
# that Nim has
template repeatTmpl(n: int, body: untyped): untyped =
for x in 0..<n:
body
# This gets rewritten into a for loop
repeatTmpl 4:
example()
import std/macros
# A macro which takes some code block and returns code
# with that code block repeated n times. Macros run at
# compile-time
macro repeatMacro(n: static[int], body: untyped): untyped =
result = newStmtList()
for x in 0..<n:
result.add body
# This gets rewritten into 4 calls to example()
# at compile-time
repeatMacro 4:
example()
Objeck
class Repeat {
function : Main(args : String[]) ~ Nil {
Repeat(Example() ~ Nil, 3);
}
function : Repeat(e : () ~ Nil, i : Int) ~ Nil {
while(i-- > 0) {
e();
};
}
function : Example() ~ Nil {
"Example"->PrintLine();
}
}
OCaml
let repeat ~f ~n =
for i = 1 to n do
f ()
done
let func () =
print_endline "Example"
let () =
repeat ~n:4 ~f:func
Oforth
This method is already defined : times. This method can be used on all runnables (functions, methods, blocks, ...).
: hello "Hello, World!" println ;
10 #hello times
- Output:
Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!
Ol
; sample function
(define (function) (display "+"))
; simple case for 80 times
(for-each (lambda (unused) (function)) (iota 80))
(print) ; print newline
; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
; detailed case for 80 times
(let loop ((fnc function) (n 80))
(unless (zero? n)
(begin
(fnc)
(loop fnc (- n 1)))))
(print) ; print newline
; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
PARI/GP
repeat(f, n)=for(i=1,n,f());
repeat( ()->print("Hi!"), 2);
- Output:
Hi! Hi!
Pascal
program Repeater;
type
TProc = procedure(I: Integer);
procedure P(I: Integer);
begin
WriteLn('Iteration ', I);
end;
procedure Iterate(P: TProc; N: Integer);
var
I: Integer;
begin
for I := 1 to N do
P(I);
end;
begin
Iterate(P, 3);
end.
- Output:
Iteration 1 Iteration 2 Iteration 3
Perl
sub repeat {
my ($sub, $n) = @_;
$sub->() for 1..$n;
}
sub example {
print "Example\n";
}
repeat(\&example, 4);
Phix
procedure Repeat(integer rid, integer n) for i=1 to n do rid() end for end procedure procedure Hello() ?"Hello" end procedure Repeat(Hello,5)
Phixmonti
def myFunc
"Sure looks like a function in here..." print nl
enddef
def rep /# func times -- #/
for drop
dup exec
endfor
drop
enddef
getid myFunc 4 rep
PicoLisp
# The built-in function "do" can be used to achieve our goal,
# however, it has a slightly different syntax than what the
# problem specifies.
# Native solution.
(do 10 (version))
# Our solution.
(de dofn (Fn N)
(do N (Fn)) )
(dofn version 10)
PowerShell
(Made more PowerShelly.)
function Out-Example
{
"Example"
}
function Step-Function ([string]$Function, [int]$Repeat)
{
for ($i = 1; $i -le $Repeat; $i++)
{
"$(Invoke-Expression -Command $Function) $i"
}
}
Step-Function Out-Example -Repeat 3
- Output:
Example 1 Example 2 Example 3
Prolog
repeat(_, 0).
repeat(Callable, Times) :-
succ(TimesLess1, Times),
Callable,
repeat(Callable, TimesLess1).
test :- write('Hello, World'), nl.
test(Name) :- format('Hello, ~w~n', Name).
- Output:
?- repeat(test, 3). Hello, World Hello, World Hello, World true ; false. ?- repeat(test('Fred'), 3). Hello, Fred Hello, Fred Hello, Fred true ; false.
PureBasic
Prototype.i fun(x.i)
Procedure.i quark(z.i)
Debug "Quark "+Str(z) : ProcedureReturn z-1
EndProcedure
Procedure rep(q.fun,n.i)
Repeat : n=q(n) : Until n=0
EndProcedure
rep(@quark(),3)
- Output:
Quark 3 Quark 2 Quark 1
Python
Procedural
#!/usr/bin/python
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.
Functional
Repeated function application:
'''Application of a given function, repeated N times'''
from itertools import repeat
from functools import reduce
from inspect import getsource
# applyN :: Int -> (a -> a) -> a -> a
def applyN(n):
'''n compounding applications of the supplied
function f. Equivalent to Church numeral n.
'''
def go(f):
return lambda x: reduce(
lambda a, g: g(a), repeat(f, n), x
)
return lambda f: go(f)
# MAIN ----------------------------------------------------
def main():
'''Tests - compounding repetition
of function application.
'''
def f(x):
return x + 'Example\n'
def g(x):
return 2 * x
def h(x):
return 1.05 * x
print(
fTable(__doc__ + ':')(
lambda fx: '\nRepeated * 3:\n (' + (
getsource(fst(fx)).strip() + ')(' +
repr(snd(fx)) + ')'
)
)(str)(
liftA2(applyN(3))(fst)(snd)
)([(f, '\n'), (g, 1), (h, 100)])
)
# GENERIC -------------------------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
# liftA2 :: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> c
def liftA2(op):
'''Lift a binary function to a composition
over two other functions.
liftA2 (*) (+ 2) (+ 3) 7 == 90
'''
def go(f, g):
return lambda x: op(
f(x)
)(g(x))
return lambda f: lambda g: go(f, g)
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
# MAIN ---
if __name__ == '__main__':
main()
- Output:
Application of a given function, repeated N times: Repeated * 3: (def f(x): return x + 'Example\n')('\n') -> Example Example Example Repeated * 3: (def g(x): return 2 * x)(1) -> 8 Repeated * 3: (def h(x): return 1.05 * x)(100) -> 115.7625
Quackery
This is a function which is part of the Quackery language. times performs the word or nest after it the number of times specified on the stack. The definition is reproduced here, along with the additional functionality included in the language; i counts down to zero, i^ counts up from zero, step specifies the increment size from an argument on the stack (default is 1), conclude sets the iteration countdown to the final value (0) and refresh sets the iteration countdown to the initial value. times is nestable, and words such as witheach (which makes use of times to iterate over a nest) inherit its additional functionality.
The word rosetta-times is also defined here, using times. It takes both the repeat number and the function as stack arguments.
[ stack ] is times.start ( --> s )
protect times.start
[ stack ] is times.count ( --> s )
protect times.count
[ stack ] is times.action ( --> s )
protect times.action
[ ]'[ times.action put
dup times.start put
[ 1 - dup -1 > while
times.count put
times.action share do
times.count take again ]
drop
times.action release
times.start release ] is times ( n --> )
[ times.count share ] is i ( --> n )
[ times.start share i 1+ - ] is i^ ( --> n )
[ 0 times.count replace ] is conclude ( --> )
[ times.start share
times.count replace ] is refresh ( --> )
[ times.count take 1+
swap - times.count put ] is step ( --> s )
[ nested ' times nested
swap join do ] is rosetta-times ( n x --> )
- Output:
rosetta-times demonstrated in the Quackery shell. (REPL)
/O> [ say "hello" cr ] is hi ... 5 ' hi rosetta-times ... hello hello hello hello hello Stack empty.
R
f1 <- function(...){print("coucou")}
f2 <-function(f,n){
lapply(seq_len(n),eval(f))
}
f2(f1,4)
Racket
The racket guide has a section called "Iterators and Comprehensions", which shows that for isn't just for repeating n times!
#lang racket/base
(define (repeat f n) ; the for loop is idiomatic of (although not exclusive to) racket
(for ((_ n)) (f)))
(define (repeat2 f n) ; This is a bit more "functional programmingy"
(when (positive? n) (f) (repeat2 f (sub1 n))))
(display "...")
(repeat (λ () (display " and over")) 5)
(display "...")
(repeat2 (λ () (display " & over")) 5)
(newline)
- Output:
... and over and over and over and over and over... & over & over & over & over & over
Raku
(formerly Perl 6)
sub repeat (&f, $n) { f() xx $n };
sub example { say rand }
repeat(&example, 3);
- Output:
0.435249779778396 0.647701200726486 0.279289335968417
Of course, we could have just written
example() xx 3;
or even
(say rand) xx 3;
directly – the custom repeat
subroutine is just here to satisfy the task description.
Notes on the xx
operator:
- Unlike other operators, it evaluates its left-hand-side argument lazily - that's why we can simply call
f()
there rather than passing it as a function object. - The operator has a return value: A list consisting of the return values of the left-hand-side (and building lists is in fact what
xx
is usually used for).
General notes:
- The
&
sigil in therepeat
subroutine signature restricts that parameter to types that implement theCallable
role, and makes it available inside therepeat
subroutine body as if it were a lexically scoped sub. - The parentheses in the last line are necessary to disambiguate it as a call to our custom subroutine, rather than an attempt to use the built-in
repeat { ... } while ...
construct.
Red
Red[]
myrepeat: function [fn n] [loop n [do fn]]
myrepeat [print "hello"] 3
- Output:
hello hello hello
Refal
$ENTRY Go {
= <Prout <Repeat 3 Example> Eggs And <Example>>;
}
Repeat {
0 s.F e.X = e.X;
s.N s.F e.X = <Repeat <- s.N 1> s.F <Mu s.F e.X>>;
};
Example {
e.X = e.X Spam;
};
- Output:
Spam Spam Spam Eggs And Spam
REXX
The procedure name (that is being repeatedly executed) isn't restricted to an internal REXX subroutine (procedure),
it may be an external program (procedure) written in any language.
/*REXX program executes a named procedure a specified number of times. */
parse arg pN # . /*obtain optional arguments from the CL*/
if #=='' | #=="," then #= 1 /*assume once if not specified. */
if pN\=='' then call repeats pN, # /*invoke the REPEATS procedure for pN.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
repeats: procedure; parse arg x,n /*obtain the procedureName & # of times*/
do n; interpret 'CALL' x; end /*repeat the invocation N times. */
return /*return to invoker of the REPEATS proc*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
yabba: say 'Yabba, yabba do!'; return /*simple code; no need for PROCEDURE.*/
- output when using the input of: yabba 4
Yabba, yabba do! Yabba, yabba do! Yabba, yabba do! Yabba, yabba do!
output when the input is: $date 3
[The (external) $DATE.REX program isn't supplied here.]
day-of-year= 159 Gregorian date= 06/08/2014 Sunday day-of-year= 159 Gregorian date= 06/08/2014 Sunday day-of-year= 159 Gregorian date= 06/08/2014 Sunday
Ring
Func Main
times(5,:test)
Func Test
see "Message from the test function!" + nl
Func Times nCount, F
for x = 1 to nCount
Call F()
next
RPL
≪ → func n ≪ 1 n START func EVAL NEXT ≫ ≫ 'TIMES' STO ≪ " world" "Hello" SWAP + ≫ 3 TIMES
- Output:
3: "Hello world" 2: "Hello world" 1: "Hello world"
Ruby
4.times{ puts "Example" } # idiomatic way
def repeat(proc,num)
num.times{ proc.call }
end
repeat(->{ puts "Example" }, 4)
Rust
Rust has higher-order functions.
fn repeat(f: impl FnMut(usize), n: usize) {
(0..n).for_each(f);
}
Here we define the function repeat
which takes the function Fn(usize)
, which is an anonymous trait constraint by the impl Trait
syntax, in such a way that it's size can be known statically at compile time. The range iterator 0..n
is used, in combination with the Iterator::for_each
method to consume it.
Closure
It's idiomatic to use a closure.
fn main() {
repeat(|x| print!("{};", x), 5);
}
- Output:
0;1;2;3;4;
Static Function
Also possible to define a static function.
fn function(x: usize) {
print!("{};", x);
}
fn main() {
repeat(function, 4);
}
- Output:
0;1;2;3;
Static Method
Sometimes it may be convenient to call a static method.
struct Foo;
impl Foo {
fn associated(x: usize) {
print!("{};", x);
}
}
fn main() {
repeat(Foo::associated, 8);
}
- Output:
0;1;2;3;4;5;6;7;
Trait Method
You can also use implemented trait-methods as a function-argument. This works because the implemented type is usize
which is what the iterator supplied to Fn(usize)
.
trait Bar {
fn run(self);
}
impl Bar for usize {
fn run(self) {
print!("{};", self);
}
}
fn main() {
repeat(Bar::run, 6);
}
- Output:
0;1;2;3;4;5;
Mutable Closure
The most interesting application would probably be a mutable closure, which requires changing the type signature from Fn
to FnMut
, because they are constrained by slightly different rules, but otherwise work the same.
fn repeat(f: impl FnMut(usize), n: usize) {
(0..n).for_each(f);
}
fn main() {
let mut mult = 1;
repeat(|x| {
print!("{};", x * mult);
mult += x;
}, 5);
}
- Output:
0;1;4;12;28;
Scala
Intuitive solution
- Call by name
- Type parameterization
- Higher order function
def repeat[A](n:Int)(f: => A)= ( 0 until n).foreach(_ => f)
repeat(3) { println("Example") }
Advanced Scala-ish
- Call by name
- Type parameterization
- Implicit method
- Tail recursion
- Infix notation
object Repeat2 extends App {
implicit class IntWithTimes(x: Int) {
def times[A](f: => A):Unit = {
@tailrec
def loop( current: Int): Unit =
if (current > 0) {
f
loop(current - 1)
}
loop(x)
}
}
5 times println("ha") // Not recommended infix for 5.times(println("ha")) aka dot notation
}
Most Scala-ish
- Call by name
- Type parameterization
- Implicit method
- Tail recursion
- Infix notation
- Operator overloading
import scala.annotation.tailrec
object Repeat3 extends App {
implicit class UnitWithNtimes(f: => Unit) {
def *[A](n: Int): Unit = { // Symbol * used instead of literal method name
@tailrec
def loop(current: Int): Unit =
if (current > 0) {
f
loop(current - 1)
}
loop(n)
}
}
print("ha") * 5 // * is the method, effective should be A.*(5)
}
Scheme
Scheme is mostly made up from expressions which return values. However some functions, such as display, return an unspecified value. The actual value returned varies depending on the Scheme implementation itself.
(import (scheme base)
(scheme write))
(define (repeat proc n)
(do ((i 0 (+ 1 i))
(res '() (cons (proc) res)))
((= i n) res)))
;; example returning an unspecified value
(display (repeat (lambda () (display "hi\n")) 4)) (newline)
;; example returning a number
(display (repeat (lambda () (+ 1 2)) 5)) (newline)
- Output:
(Using chibi-scheme: returns #<undef> from display.)
hi hi hi hi (#<undef> #<undef> #<undef> #<undef>) (3 3 3 3 3)
Seed7
$ include "seed7_05.s7i";
const proc: myRepeat (in integer: times, in proc: aProcedure) is func
local
var integer: n is 0;
begin
for n range 1 to times do
aProcedure;
end for;
end func;
const proc: main is func
begin
myRepeat(3, writeln("Hello!"));
end func;
- Output:
Hello! Hello! Hello!
Sidef
func repeat(f, n) {
{ f() } * n;
}
func example {
say "Example";
}
repeat(example, 4);
Standard ML
fun repeat (_, 0) = ()
| repeat (f, n) = (f (); repeat (f, n - 1))
fun testProcedure () =
print "test\n"
val () = repeat (testProcedure, 5)
Stata
function repeat(f,n) {
for (i=1; i<=n; i++) (*f)()
}
function hello() {
printf("Hello\n")
}
repeat(&hello(),3)
Swift
func repeat(n: Int, f: () -> ()) {
for _ in 0..<n {
f()
}
}
repeat(4) { println("Example") }
Tcl
The usual way of doing a repeat would be:
proc repeat {command count} {
for {set i 0} {$i < $count} {incr i} {
uplevel 1 $command
}
}
proc example {} {puts "This is an example"}
repeat example 4
However, the time
command can be used as long as the return value (the report on the timing information) is ignored.
time example 4
It should be noted that the “command” can be an arbitrary script, not just a call to a procedure:
repeat {puts "hello world"} 3
uBasic/4tH
Proc _Repeat (_HelloWorld, 5) : End
_Repeat Param (2) : Local (1) : For c@ = 1 To b@ : Proc a@ : Next : Return
_HelloWorld Print "Hello world!" : Return
Output:
Hello world! Hello world! Hello world! Hello world! Hello world! 0 OK, 0:35
Ursa
def repeat (function f, int n)
for (set n n) (> n 0) (dec n)
f
end for
end repeat
def procedure ()
out "Hello! " console
end procedure
# outputs "Hello! " 5 times
repeat procedure 5
VBA
Private Sub Repeat(rid As String, n As Integer)
For i = 1 To n
Application.Run rid
Next i
End Sub
Private Sub Hello()
Debug.Print "Hello"
End Sub
Public Sub main()
Repeat "Hello", 5
End Sub
Verilog
module main;
initial begin
repeat(5) begin
$display("Inside loop");
end
$display("Loop Ended");
end
endmodule
- Output:
Inside loop Inside loop Inside loop Inside loop Inside loop Loop Ended
Visual Basic .NET
Module Module1
Sub Repeat(count As Integer, fn As Action(Of Integer))
If IsNothing(fn) Then
Throw New ArgumentNullException("fn")
End If
For i = 1 To count
fn.Invoke(i)
Next
End Sub
Sub Main()
Repeat(3, Sub(x) Console.WriteLine("Example {0}", x))
End Sub
End Module
- Output:
Example 1 Example 2 Example 3
V (Vlang)
fn repeat(n int, f fn()) {
for _ in 0.. n {
f()
}
}
fn func() {
println("Example")
}
fn main() {
repeat(4, func)
}
- Output:
Example Example Example Example
Wren
var f = Fn.new { |g, n|
for (i in 1..n) g.call(n)
}
var g = Fn.new { |k|
for (i in 1..k) System.write("%(i) ")
System.print()
}
f.call(g, 5)
- Output:
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
XBS
XBS has a built-in repeat keyword.
func rep(callback:function,amount:number,*args:array=[]):null{
repeat amount {
callback(*args);
}
}
rep(func(a,b,c){
log(a+b+c);
},3,1,2,3);
- Output:
6 6 6
XLISP
(defun repeat (f n)
(f)
(if (> n 1)
(repeat f (- n 1)) ) )
;; an example to test it:
(repeat (lambda () (print '(hello rosetta code))) 5)
- Output:
(HELLO ROSETTA CODE) (HELLO ROSETTA CODE) (HELLO ROSETTA CODE) (HELLO ROSETTA CODE) (HELLO ROSETTA CODE)
Yabasic
sub myFunc ()
print "Sure looks like a function in here..."
end sub
sub rep (func$, times)
for count = 1 to times
execute(func$)
next
end sub
rep("myFunc", 4)
Z80 Assembly
Return Trick
This technique is called the "Return Trick", it's efficient but makes the program more difficult to read. It works on the principle that the processor's RET command assumes the return address is the top item of the stack. The programmer can abuse this to "return" to a section of code that has never actually been executed. This is essentially just another form of the computed goto. Most processors that use the stack to store return addresses can use this technique, though the method of doing it depends on the processor itself.
ld b,&05 ;load the decrement value into b
ld hl,myFunc ;load the address of "myFunc" into HL
call repeatProcedure
forever:
jp forever ;trap the program counter here
repeatProcedure: ;input: b = times to repeat, hl = which procedure to repeat
call trampoline
; the "ret" in myFunc will bring you here
djnz repeatProcedure
ret ;exit "repeatProcedure" and proceed to "forever"
trampoline:
push hl
ret
;this is effectively a call to whatever is in HL, in this case "myFunc." The "ret" at the end of myFunc will return us to
;just after the line "call trampoline"
myFunc: ;this doesn't do anything useful but that's not the point
push hl ;not needed for this routine but if it altered HL we would need this so that we come back here next time we loop
or a
pop hl
ret
Indirect Jump
Same as above but uses an indirect jump to the address in HL.
trampoline:
jp (hl) ;despite the parentheses this does NOT dereference HL, it merely acts as "LD PC,HL".
Using self-modifying code
This method assumes the routine doesn't use the B register, or restores it before returning. Also, the actual "wrapper" used to repeat the passed function must be in RAM so that its instructions can be modified at runtime.
LD HL,myFunc
LD (repeatproc+1),HL
LD B,5 ;repeat count
CALL repeatProc
;somewhere far away from here:
repeatProc:
call &0000 ;gets overwritten with the address of MyFunc
djnz repeatProc
ret
zkl
fcn repeat(f,n){ do(n){ f() } }
repeat("ho ".print,3);
- Output:
ho ho ho
- Programming Tasks
- Solutions by Programming Task
- 11l
- 6502 Assembly
- 68000 Assembly
- Action!
- Ada
- ALGOL 68
- ALGOL W
- AppleScript
- Applesoft BASIC
- Arturo
- AutoHotkey
- AWK
- BASIC
- BASIC256
- Chipmunk Basic
- GW-BASIC
- Minimal BASIC
- MSX Basic
- QBasic
- Quite BASIC
- True BASIC
- XBasic
- Batch File
- BQN
- C
- C sharp
- C++
- Chapel
- Clojure
- Common Lisp
- Cowgol
- D
- Delphi
- EchoLisp
- F Sharp
- Factor
- Fe
- Forth
- FreeBASIC
- FutureBasic
- Gambas
- Go
- Haskell
- Isabelle
- J
- Java
- Jq
- Julia
- Kotlin
- Lean
- LiveCode
- Lua
- Mastermind
- Mathematica
- Wolfram Language
- Min
- MiniScript
- МК-61/52
- Modula-2
- Nanoquery
- Nim
- Objeck
- OCaml
- Oforth
- Ol
- PARI/GP
- Pascal
- Perl
- Phix
- Phixmonti
- PicoLisp
- PowerShell
- Prolog
- PureBasic
- Python
- Quackery
- R
- Racket
- Raku
- Red
- Refal
- REXX
- Ring
- RPL
- Ruby
- Rust
- Scala
- Scheme
- Seed7
- Sidef
- Standard ML
- Stata
- Swift
- Tcl
- UBasic/4tH
- Ursa
- VBA
- Verilog
- Visual Basic .NET
- V (Vlang)
- Wren
- XBS
- XLISP
- Yabasic
- Z80 Assembly
- Zkl