Repeat: Difference between revisions

17,838 bytes added ,  16 days ago
m
Applesoft BASIC - fixed broken link, included code from linked web page
m (→‎{{header|Phix}}: added syntax colouring the hard way)
m (Applesoft BASIC - fixed broken link, included code from linked web page)
(35 intermediate revisions by 20 users not shown)
Line 10:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F repeat(f, n)
L 1..n
f()
Line 17:
print(‘Example’)
 
repeat(procedure, 3)</langsyntaxhighlight>
 
{{out}}
Line 24:
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}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Repeat_Example is
Line 46 ⟶ 164:
begin
Repeat(Hello'Access, 3); -- Hello'Access points to the procedure Hello
end Repeat_Example;</langsyntaxhighlight>
 
Output:
Line 53 ⟶ 171:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68">
# operator that executes a procedure the specified number of times #
OP REPEAT = ( INT count, PROC VOID routine )VOID:
Line 79 ⟶ 197:
 
)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 92 ⟶ 210:
=={{header|ALGOL W}}==
As well as the names of procedures, Algol W allows statements to be passed as parameters where a procedure is expected.
<langsyntaxhighlight lang="algolw">begin
% executes the procedure routine the specified number of times %
procedure repeat ( integer value count; procedure routine ) ;
Line 110 ⟶ 228:
)
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 120 ⟶ 238:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">-- applyN :: Int -> (a -> a) -> a -> a
on applyN(n, f, x)
script go
Line 202 ⟶ 320:
end repeat
return out & dbl
end replicate</langsyntaxhighlight>
{{Out}}
<pre>(*1024*)
Line 209 ⟶ 327:
 
=={{header|Applesoft BASIC}}==
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}}==
<langsyntaxhighlight lang="rebol">print "---------------------------"
print "As a loop"
print "---------------------------"
Line 236 ⟶ 375:
print "With a function param"
print "---------------------------"
repeatFunc $[][print "Example 3"] 4</langsyntaxhighlight>
 
{{out}}
Line 263 ⟶ 402:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">repeat("fMsgBox",3)
return
 
Line 273 ⟶ 412:
fMsgBox(){
MsgBox hello
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f REPEAT.AWK
BEGIN {
Line 295 ⟶ 434:
}
}
</syntaxhighlight>
</lang>
<p>output:</p>
<pre>
Line 305 ⟶ 444:
inside odd 3
</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}}==
<langsyntaxhighlight lang="dos">
@echo off
 
Line 325 ⟶ 602:
echo _func2 has been executed
exit /b
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void repeat(void (*f)(void), unsigned int n) {
Line 343 ⟶ 631:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
 
namespace Repeat {
Line 364 ⟶ 652:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Example 1
Line 371 ⟶ 659:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">template <typename Function>
void repeat(Function f, unsigned int n) {
for(unsigned int i=n; 0<i; i--)
f();
}</langsyntaxhighlight>
usage:
<langsyntaxhighlight lang="cpp">#include <iostream>
void example() {
std::cout << "Example\n";
}
 
repeat(example, 4);</langsyntaxhighlight>
{{works with|C++11}}
<langsyntaxhighlight lang="cpp"> repeat([]{std::cout << "Example\n";}, 4);</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn repeat-function [f n]
(dotimes [i n] (f)))</langsyntaxhighlight>
 
{{out}}
Line 397 ⟶ 685:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun repeat (f n)
(dotimes (i n) (funcall f)))
 
(repeat (lambda () (format T "Example~%")) 5)</langsyntaxhighlight>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
# Only functions that implement an interface can be passed around
Line 425 ⟶ 713:
# Prints "foo foo foo foo"
Repeat(Foo, 4);
print_nl(); </langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void repeat(void function() fun, in uint times) {
foreach (immutable _; 0 .. times)
fun();
Line 440 ⟶ 728:
void main() {
repeat(&procedure, 3);
}</langsyntaxhighlight>
{{out}}
<pre>Example
Line 447 ⟶ 735:
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
program Repeater;
 
Line 475 ⟶ 763:
end.
 
</syntaxhighlight>
</lang>
 
Alternative
 
<syntaxhighlight lang="delphi">
<lang Delphi>
program Repeater;
 
Line 504 ⟶ 792:
readln;
end.
</syntaxhighlight>
</lang>
 
 
Line 513 ⟶ 801:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(define (repeat f n) (for ((i n)) (f)))
 
Line 527 ⟶ 815:
(cos 0.7390851332151605)
→ 0.7390851332151608 ;; fixed point found
</syntaxhighlight>
</lang>
 
=={{header|F#|F sharp}}==
<langsyntaxhighlight lang="fsharp">open System
 
let Repeat c f =
Line 543 ⟶ 831:
Repeat 3 Hello
 
0 // return an integer exit code</langsyntaxhighlight>
 
=={{header|Factor}}==
Factor comes with the <tt>times</tt> word which does exactly this. For example,
<langsyntaxhighlight lang="factor">3 [ "Hello!" print ] times</langsyntaxhighlight>
{{out}}
<pre>
Line 556 ⟶ 844:
 
The implementation of <tt>times</tt>:
<langsyntaxhighlight lang="factor">: times ( ... n quot: ( ... -- ... ) -- ... )
[ drop ] prepose each-integer ; inline</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="forth">: times ( xt n -- )
0 ?do dup execute loop drop ;</langsyntaxhighlight>
 
Or, taking care to keep the data stack clean for the XT's use, as is often desired:
 
<langsyntaxhighlight lang="forth">: times { xt n -- }
n 0 ?do xt execute loop ;</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="forth">: times[ ]] 0 ?do [[ ; immediate compile-only
: ]times postpone loop ; immediate compile-only</langsyntaxhighlight>
 
Usage:
 
<langsyntaxhighlight lang="forth">[: cr ." Hello" ;] 3 times
 
: 3-byes ( -- ) 3 times[ cr ." Bye" ]times ;
3-byes</langsyntaxhighlight>
 
{{out}}<pre>Hello
Line 588 ⟶ 892:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub proc()
Line 604 ⟶ 908:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 613 ⟶ 917:
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.
<langsyntaxhighlight lang="gambas">
Public Sub Main()
 
Line 645 ⟶ 978:
Print "RepeatableTwo"
 
End</langsyntaxhighlight>
Output:
<pre>
Line 656 ⟶ 989:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 672 ⟶ 1,005:
func main() {
repeat(4, fn)
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Such a function already exists
<langsyntaxhighlight Haskelllang="haskell">import Control.Monad (replicateM_)
 
sampleFunction :: IO ()
sampleFunction = putStrLn "a"
 
main = replicateM_ 5 sampleFunction</langsyntaxhighlight>
 
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:
<langsyntaxhighlight Haskelllang="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</langsyntaxhighlight>
{{Out}}
<pre>1024</pre>
Line 694 ⟶ 1,027:
=={{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.
<langsyntaxhighlight Isabellelang="isabelle">theory Scratch
imports Main
begin
Line 748 ⟶ 1,081:
lemma "fun_repeat (λ_. a) n = repeat a n" by(induction n) simp+
 
end</langsyntaxhighlight>
 
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
NB. ^: (J's power conjunction) repeatedly evaluates a verb.
 
Line 805 ⟶ 1,138:
hi
hi
</syntaxhighlight>
</lang>
 
=={{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}}
<langsyntaxhighlight lang="java">import java.util.function.Consumer;
import java.util.stream.IntStream;
 
Line 821 ⟶ 1,182:
IntStream.range(0, n).forEach(i -> fun.accept(i + 1));
}
}</langsyntaxhighlight>
 
Output:
Line 843 ⟶ 1,204:
 
'''Unoptimized version''':
<langsyntaxhighlight lang="jq">def unoptimized_repeat(f; n):
if n <= 0 then empty
else f, repeat(f; n-1)
end;</langsyntaxhighlight>
 
'''Optimized for TCO''':
<langsyntaxhighlight lang="jq">def repeat(f; n):
# state: [count, in]
def r:
if .[0] >= n then empty else (.[1] | f), (.[0] += 1 | r) end;
[0, .] | r;</langsyntaxhighlight>
'''Variant''':
<langsyntaxhighlight lang="jq"># 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):
Line 863 ⟶ 1,224:
else .[1], ([.[0] - 1, (.[1] | f)] | r)
end;
[n, .] | r;</langsyntaxhighlight>
 
'''Examples''':
<langsyntaxhighlight lang="jq">0 | [ repeat(.+1; 3) ]</langsyntaxhighlight>
produces:
[1,1,1]
<langsyntaxhighlight lang="jq">0 | repeatedly(.+1; 3)</langsyntaxhighlight>
produces:
0
Line 877 ⟶ 1,238:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function sayHi()
println("Hi")
end
Line 885 ⟶ 1,246:
end
 
rep(sayHi, 3)</langsyntaxhighlight>
{{out}}
<pre>Hi
Line 892 ⟶ 1,253:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun repeat(n: Int, f: () -> Unit) {
Line 903 ⟶ 1,264:
fun main(args: Array<String>) {
repeat(5) { print("Example ") }
}</langsyntaxhighlight>
 
{{out}}
Line 916 ⟶ 1,277:
=={{header|Lean}}==
 
It runs on ===Lean 3.4.2:===
<syntaxhighlight lang="lean">
 
<lang Lean>def repeat : ℕ → (ℕ → string) → string
| 0 f := "done"
| (n + 1) f := (f n) ++ (repeat n f)
Line 924 ⟶ 1,285:
 
#eval repeat 5 $ λ b : ℕ , "me "
</syntaxhighlight>
</lang>
 
{{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}}==
<langsyntaxhighlight LiveCodelang="livecode">rep "answer",3
 
command rep x,n
Line 933 ⟶ 1,317:
do merge("[[x]] [[n]]")
end repeat
end rep</langsyntaxhighlight>
 
=={{header|Lua}}==
No particular magic required as Lua allows functions to be passed as arguments.
<langsyntaxhighlight Lualang="lua">function myFunc ()
print("Sure looks like a function in here...")
end
Line 948 ⟶ 1,332:
 
rep(myFunc, 4)
</syntaxhighlight>
</lang>
{{out}}
<pre>Sure looks like a function in here...
Line 955 ⟶ 1,339:
Sure looks like a function in here...</pre>
 
=={{header|MathematicaMastermind}}==
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.
<langsyntaxhighlight Mathematicalang="mathematica">repeat[f_, n_] := Do[f[], {n}];
repeat[Print["Hello, world!"] &, 5];</langsyntaxhighlight>
{{out}}
<pre>Hello, world!
Line 969 ⟶ 1,381:
This operator already exists in min and is called <code>times</code>.
{{works with|min|0.19.6}}
<langsyntaxhighlight lang="min">("Hello" puts!) 3 times</langsyntaxhighlight>
{{out}}
<pre>
Line 979 ⟶ 1,391:
=={{header|MiniScript}}==
 
<langsyntaxhighlight MiniScriptlang="miniscript">sayHi = function()
print "Hi!"
end function
Line 989 ⟶ 1,401:
end function
 
rep @sayHi, 3</langsyntaxhighlight>
{{out}}
<pre>Hi!
Line 997 ⟶ 1,409:
=={{header|МК-61/52}}==
 
<syntaxhighlight lang="text">1 П4
 
3 ^ 1 6 ПП 09 С/П
Line 1,003 ⟶ 1,415:
П7 <-> П0 КПП7 L0 12 В/О
 
ИП4 С/П КИП4 В/О</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Repeat;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
 
Line 1,029 ⟶ 1,441:
 
ReadChar
END Repeat.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def repeat(f,n)
for i in range(1, n)
f()
Line 1,043 ⟶ 1,455:
end
 
repeat(procedure, 3)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc example =
echo "Example"
 
Line 1,080 ⟶ 1,492:
repeatMacro 4:
example()
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
 
<langsyntaxhighlight lang="objeck">class Repeat {
function : Main(args : String[]) ~ Nil {
Repeat(Example() ~ Nil, 3);
Line 1,098 ⟶ 1,510:
"Example"->PrintLine();
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let repeat ~f ~n =
for i = 1 to n do
f ()
Line 1,112 ⟶ 1,524:
let () =
repeat ~n:4 ~f:func
</syntaxhighlight>
</lang>
 
=={{header|Oforth}}==
Line 1,118 ⟶ 1,530:
This method is already defined : times. This method can be used on all runnables (functions, methods, blocks, ...).
 
<langsyntaxhighlight Oforthlang="oforth">: hello "Hello, World!" println ;
10 #hello times</langsyntaxhighlight>
 
{{out}}
Line 1,136 ⟶ 1,548:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
; sample function
(define (function) (display "+"))
Line 1,153 ⟶ 1,565:
(print) ; print newline
; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">repeat(f, n)=for(i=1,n,f());
repeat( ()->print("Hi!"), 2);</langsyntaxhighlight>
{{out}}
<pre>Hi!
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}}==
Line 1,166 ⟶ 1,604:
{{trans|C}}
 
<langsyntaxhighlight lang="perl">sub repeat {
my ($sub, $n) = @_;
$sub->() for 1..$n;
Line 1,175 ⟶ 1,613:
}
 
repeat(\&example, 4);</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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>
Line 1,190 ⟶ 1,628:
<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>
<!--</langsyntaxhighlight>-->
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def myFunc
"Sure looks like a function in here..." print nl
enddef
Line 1,205 ⟶ 1,643:
 
getid myFunc 4 rep
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
 
<langsyntaxhighlight PicoLisplang="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.
Line 1,220 ⟶ 1,658:
(do N (Fn)) )
 
(dofn version 10)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
{{trans|Python}} (Made more PowerShelly.)
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Out-Example
{
Line 1,239 ⟶ 1,677:
 
Step-Function Out-Example -Repeat 3
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,249 ⟶ 1,687:
=={{header|Prolog}}==
 
<langsyntaxhighlight lang="prolog">repeat(_, 0).
repeat(Callable, Times) :-
succ(TimesLess1, Times),
Line 1,256 ⟶ 1,694:
 
test :- write('Hello, World'), nl.
test(Name) :- format('Hello, ~w~n', Name).</langsyntaxhighlight>
{{out}}
<pre>
Line 1,275 ⟶ 1,713:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Prototype.i fun(x.i)
 
Procedure.i quark(z.i)
Line 1,285 ⟶ 1,723:
EndProcedure
 
rep(@quark(),3)</langsyntaxhighlight>
{{out}}
<pre>Quark 3
Line 1,294 ⟶ 1,732:
 
===Procedural===
<langsyntaxhighlight Pythonlang="python">#!/usr/bin/python
def repeat(f,n):
for i in range(n):
Line 1,302 ⟶ 1,740:
print("Example");
 
repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.</langsyntaxhighlight>
 
===Functional===
Repeated function application:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Application of a given function, repeated N times'''
 
from itertools import repeat
Line 1,405 ⟶ 1,843:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Application of a given function, repeated N times:
Line 1,431 ⟶ 1,869:
The word ''rosetta-times'' is also defined here, using ''times''. It takes both the repeat number and the function as stack arguments.
 
<langsyntaxhighlight Quackerylang="quackery"> [ stack ] is times.start ( --> s )
protect times.start
 
Line 1,463 ⟶ 1,901:
 
[ nested ' times nested
swap join do ] is rosetta-times ( n x --> )</langsyntaxhighlight>
 
{{Out}}
Line 1,479 ⟶ 1,917:
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
f1 <- function(...){print("coucou")}
 
Line 1,487 ⟶ 1,925:
 
f2(f1,4)
</syntaxhighlight>
</lang>
 
=={{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!
 
<langsyntaxhighlight Racketlang="racket">#lang racket/base
(define (repeat f n) ; the for loop is idiomatic of (although not exclusive to) racket
(for ((_ n)) (f)))
Line 1,503 ⟶ 1,941:
(display "...")
(repeat2 (λ () (display " & over")) 5)
(newline)</langsyntaxhighlight>
{{out}}
<pre>... and over and over and over and over and over... & over & over & over & over & over</pre>
Line 1,510 ⟶ 1,948:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>sub repeat (&f, $n) { f() xx $n };
 
sub example { say rand }
 
repeat(&example, 3);</langsyntaxhighlight>
 
{{Out}}
Line 1,533 ⟶ 1,971:
* 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}}==
The procedure name (that is being repeatedly executed) isn't restricted to an &nbsp; ''internal'' &nbsp; REXX subroutine (procedure),
<br>it may be an &nbsp; ''external'' &nbsp; program (procedure) written in any language.
<langsyntaxhighlight lang="rexx">/*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. */
Line 1,547 ⟶ 2,014:
return /*return to invoker of the REPEATS proc*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
yabba: say 'Yabba, yabba do!'; return /*simple code; no need for PROCEDURE.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> yabba &nbsp; 4 </tt>}}
<pre>
Line 1,565 ⟶ 2,032:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Func Main
times(5,:test)
Line 1,576 ⟶ 2,043:
Call F()
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}}==
<langsyntaxhighlight lang="ruby">4.times{ puts "Example" } # idiomatic way
 
def repeat(proc,num)
Line 1,585 ⟶ 2,065:
end
 
repeat(->{ puts "Example" }, 4)</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 1,591 ⟶ 2,071:
Rust has higher-order functions.
 
<langsyntaxhighlight lang="rust">fn repeat(f: impl FnMut(usize), n: usize) {
(0..n).for_each(f);
}</langsyntaxhighlight>
 
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.
Line 1,601 ⟶ 2,081:
It's idiomatic to use a closure.
 
<langsyntaxhighlight lang="rust">fn main() {
repeat(|x| print!("{};", x), 5);
}</langsyntaxhighlight>
{{out}}<pre>0;1;2;3;4;</pre>
 
Line 1,610 ⟶ 2,090:
Also possible to define a static function.
 
<langsyntaxhighlight lang="rust">fn function(x: usize) {
print!("{};", x);
}
Line 1,616 ⟶ 2,096:
fn main() {
repeat(function, 4);
}</langsyntaxhighlight>
 
{{out}}<pre>0;1;2;3;</pre>
Line 1,624 ⟶ 2,104:
Sometimes it may be convenient to call a static method.
 
<langsyntaxhighlight lang="rust">struct Foo;
impl Foo {
fn associated(x: usize) {
Line 1,633 ⟶ 2,113:
fn main() {
repeat(Foo::associated, 8);
}</langsyntaxhighlight>
{{out}}<pre>0;1;2;3;4;5;6;7;</pre>
 
Line 1,640 ⟶ 2,120:
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>.
 
<langsyntaxhighlight lang="rust">trait Bar {
fn run(self);
}
Line 1,652 ⟶ 2,132:
fn main() {
repeat(Bar::run, 6);
}</langsyntaxhighlight>
{{out}}<pre>0;1;2;3;4;5;</pre>
 
Line 1,659 ⟶ 2,139:
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.
 
<langsyntaxhighlight lang="rust">fn repeat(f: impl FnMut(usize), n: usize) {
(0..n).for_each(f);
}
Line 1,669 ⟶ 2,149:
mult += x;
}, 5);
}</langsyntaxhighlight>
{{out}}<pre>0;1;4;12;28;</pre>
 
Line 1,677 ⟶ 2,157:
# Type parameterization
# Higher order function
<langsyntaxhighlight lang="scala"> def repeat[A](n:Int)(f: => A)= ( 0 until n).foreach(_ => f)
 
repeat(3) { println("Example") }</langsyntaxhighlight>
===Advanced Scala-ish ===
# Call by name
Line 1,686 ⟶ 2,166:
# Tail recursion
# Infix notation
<langsyntaxhighlight lang="scala">object Repeat2 extends App {
implicit class IntWithTimes(x: Int) {
Line 1,701 ⟶ 2,181:
 
5 times println("ha") // Not recommended infix for 5.times(println("ha")) aka dot notation
}</langsyntaxhighlight>
 
===Most Scala-ish ===
Line 1,710 ⟶ 2,190:
# Infix notation
# Operator overloading
<langsyntaxhighlight lang="scala">import scala.annotation.tailrec
 
object Repeat3 extends App {
Line 1,727 ⟶ 2,207:
 
print("ha") * 5 // * is the method, effective should be A.*(5)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Line 1,734 ⟶ 2,214:
an unspecified value. The actual value returned varies depending on the Scheme implementation itself.
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write))
Line 1,748 ⟶ 2,228:
;; example returning a number
(display (repeat (lambda () (+ 1 2)) 5)) (newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,760 ⟶ 2,240:
(#<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}}==
<langsyntaxhighlight lang="ruby">func repeat(f, n) {
{ f() } * n;
}
Line 1,771 ⟶ 2,274:
}
 
repeat(example, 4);</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun repeat (_, 0) = ()
| repeat (f, n) = (f (); repeat (f, n - 1))
 
Line 1,780 ⟶ 2,283:
print "test\n"
 
val () = repeat (testProcedure, 5)</langsyntaxhighlight>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">function repeat(f,n) {
for (i=1; i<=n; i++) (*f)()
}
Line 1,792 ⟶ 2,295:
}
 
repeat(&hello(),3)</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func repeat(n: Int, f: () -> ()) {
for _ in 0..<n {
f()
Line 1,801 ⟶ 2,304:
}
 
repeat(4) { println("Example") }</langsyntaxhighlight>
 
=={{header|Tcl}}==
The usual way of doing a repeat would be:
<langsyntaxhighlight lang="tcl">proc repeat {command count} {
for {set i 0} {$i < $count} {incr i} {
uplevel 1 $command
Line 1,812 ⟶ 2,315:
 
proc example {} {puts "This is an example"}
repeat example 4</langsyntaxhighlight>
However, the <code>time</code> command can be used as long as the return value (the report on the timing information) is ignored.
<syntaxhighlight lang ="tcl">time example 4</langsyntaxhighlight>
It should be noted that the “command” can be an arbitrary script, not just a call to a procedure:
<langsyntaxhighlight lang="tcl">repeat {puts "hello world"} 3</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="ursa">def repeat (function f, int n)
for (set n n) (> n 0) (dec n)
f
Line 1,830 ⟶ 2,349:
 
# outputs "Hello! " 5 times
repeat procedure 5</langsyntaxhighlight>
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Private Sub Repeat(rid As String, n As Integer)
For i = 1 To n
Application.Run rid
Line 1,845 ⟶ 2,364:
Public Sub main()
Repeat "Hello", 5
End Sub</langsyntaxhighlight>
 
=={{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#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Repeat(count As Integer, fn As Action(Of Integer))
Line 1,865 ⟶ 2,401:
End Sub
 
End Module</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight ecmascriptlang="wren">var f = Fn.new { |g, n|
for (i in 1..n) g.call(n)
}
Line 1,881 ⟶ 2,438:
}
 
f.call(g, 5)</langsyntaxhighlight>
 
{{out}}
Line 1,890 ⟶ 2,447:
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}}==
<langsyntaxhighlight lang="lisp">(defun repeat (f n)
(f)
(if (> n 1)
Line 1,899 ⟶ 2,474:
 
;; an example to test it:
(repeat (lambda () (print '(hello rosetta code))) 5)</langsyntaxhighlight>
{{out}}
<pre>(HELLO ROSETTA CODE)
Line 1,909 ⟶ 2,484:
=={{header|Yabasic}}==
{{trans|Lua}}
<langsyntaxhighlight Yabasiclang="yabasic">sub myFunc ()
print "Sure looks like a function in here..."
end sub
Line 1,919 ⟶ 2,494:
end sub
rep("myFunc", 4)</langsyntaxhighlight>
=={{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}}==
<langsyntaxhighlight lang="zkl">fcn repeat(f,n){ do(n){ f() } }
repeat("ho ".print,3);</langsyntaxhighlight>
{{out}}<pre>ho ho ho </pre>
413

edits