Repeat: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 10: | Line 10: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F repeat(f, n) |
||
L 1..n |
L 1..n |
||
f() |
f() |
||
Line 17: | Line 17: | ||
print(‘Example’) |
print(‘Example’) |
||
repeat(procedure, 3)</ |
repeat(procedure, 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 30: | Line 30: | ||
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. |
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: |
; input: |
||
; addr = the label of the routine you wish to call repeatedly |
; addr = the label of the routine you wish to call repeatedly |
||
Line 56: | Line 56: | ||
;JMP (z_L) and it will automatically replace it with the above during the assembly process. |
;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" |
;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.</ |
;and flow into the loop overhead.</syntaxhighlight> |
||
Once the macro and the underlying subroutine are created, this is very simple to use: |
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=== |
===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. |
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 |
;input: low byte of desired function address in A |
||
; high byte of desired function address in X |
; high byte of desired function address in X |
||
Line 73: | Line 73: | ||
dey |
dey |
||
bne smc_repeatproc |
bne smc_repeatproc |
||
rts</ |
rts</syntaxhighlight> |
||
=={{header|68000 Assembly}}== |
=={{header|68000 Assembly}}== |
||
This example code prints an exclamation point to the screen 4 times. |
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.") |
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 |
move.w #4-1,d7 ;times to repeat |
||
jsr Repeater |
jsr Repeater |
||
Line 96: | Line 96: | ||
MOVE.B #'!',D0 |
MOVE.B #'!',D0 |
||
JSR PrintChar |
JSR PrintChar |
||
rts</ |
rts</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 102: | Line 102: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">DEFINE PTR="CARD" |
||
PROC OutputText(CHAR ARRAY s) |
PROC OutputText(CHAR ARRAY s) |
||
Line 133: | Line 133: | ||
PROC Main() |
PROC Main() |
||
Repeat(OutputText,"Action!",5) |
Repeat(OutputText,"Action!",5) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Repeat.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Repeat.png Screenshot from Atari 8-bit computer] |
||
Line 146: | Line 146: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
procedure Repeat_Example is |
procedure Repeat_Example is |
||
Line 164: | 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 171: | 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 197: | Line 197: | ||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 210: | Line 210: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
As well as the names of procedures, Algol W allows statements to be passed as parameters where a procedure is expected. |
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 % |
% executes the procedure routine the specified number of times % |
||
procedure repeat ( integer value count; procedure routine ) ; |
procedure repeat ( integer value count; procedure routine ) ; |
||
Line 228: | Line 228: | ||
) |
) |
||
end |
end |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 238: | Line 238: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">-- applyN :: Int -> (a -> a) -> a -> a |
||
on applyN(n, f, x) |
on applyN(n, f, x) |
||
script go |
script go |
||
Line 320: | Line 320: | ||
end repeat |
end repeat |
||
return out & dbl |
return out & dbl |
||
end replicate</ |
end replicate</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>(*1024*) |
<pre>(*1024*) |
||
Line 330: | Line 330: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">print "---------------------------" |
||
print "As a loop" |
print "As a loop" |
||
print "---------------------------" |
print "---------------------------" |
||
Line 354: | Line 354: | ||
print "With a function param" |
print "With a function param" |
||
print "---------------------------" |
print "---------------------------" |
||
repeatFunc $[][print "Example 3"] 4</ |
repeatFunc $[][print "Example 3"] 4</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 381: | Line 381: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">repeat("fMsgBox",3) |
||
return |
return |
||
Line 391: | Line 391: | ||
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 413: | Line 413: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
<p>output:</p> |
<p>output:</p> |
||
<pre> |
<pre> |
||
Line 425: | Line 425: | ||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos"> |
||
@echo off |
@echo off |
||
Line 443: | Line 443: | ||
echo _func2 has been executed |
echo _func2 has been executed |
||
exit /b |
exit /b |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
Line 449: | Line 449: | ||
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. |
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)𝔽)𝕩} |
_repeat_ ← {(𝕘>0)◶⊢‿(𝔽_𝕣_(𝕘-1)𝔽)𝕩} |
||
•Show {2+𝕩} _repeat_ 3 1</ |
•Show {2+𝕩} _repeat_ 3 1</syntaxhighlight><syntaxhighlight lang="text">7 |
||
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 472: | Line 472: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
namespace Repeat { |
namespace Repeat { |
||
Line 493: | Line 493: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Example 1 |
<pre>Example 1 |
||
Line 500: | Line 500: | ||
=={{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|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(defn repeat-function [f n] |
||
(dotimes [i n] (f)))</ |
(dotimes [i n] (f)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 526: | Line 526: | ||
=={{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}}== |
=={{header|Cowgol}}== |
||
< |
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
||
# Only functions that implement an interface can be passed around |
# Only functions that implement an interface can be passed around |
||
Line 554: | Line 554: | ||
# Prints "foo foo foo foo" |
# Prints "foo foo foo foo" |
||
Repeat(Foo, 4); |
Repeat(Foo, 4); |
||
print_nl(); </ |
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 569: | Line 569: | ||
void main() { |
void main() { |
||
repeat(&procedure, 3); |
repeat(&procedure, 3); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Example |
<pre>Example |
||
Line 576: | Line 576: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Repeater; |
program Repeater; |
||
Line 604: | Line 604: | ||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Alternative |
Alternative |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Repeater; |
program Repeater; |
||
Line 633: | Line 633: | ||
readln; |
readln; |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Line 642: | Line 642: | ||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(define (repeat f n) (for ((i n)) (f))) |
(define (repeat f n) (for ((i n)) (f))) |
||
Line 656: | Line 656: | ||
(cos 0.7390851332151605) |
(cos 0.7390851332151605) |
||
→ 0.7390851332151608 ;; fixed point found |
→ 0.7390851332151608 ;; fixed point found |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F#|F sharp}}== |
=={{header|F#|F sharp}}== |
||
< |
<syntaxhighlight lang="fsharp">open System |
||
let Repeat c f = |
let Repeat c f = |
||
Line 672: | Line 672: | ||
Repeat 3 Hello |
Repeat 3 Hello |
||
0 // return an integer exit code</ |
0 // return an integer exit code</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Factor comes with the <tt>times</tt> word which does exactly this. For example, |
Factor comes with the <tt>times</tt> word which does exactly this. For example, |
||
< |
<syntaxhighlight lang="factor">3 [ "Hello!" print ] times</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 685: | Line 685: | ||
The implementation of <tt>times</tt>: |
The implementation of <tt>times</tt>: |
||
< |
<syntaxhighlight lang="factor">: times ( ... n quot: ( ... -- ... ) -- ... ) |
||
[ drop ] prepose each-integer ; inline</ |
[ drop ] prepose each-integer ; inline</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 717: | Line 717: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Sub proc() |
Sub proc() |
||
Line 733: | Line 733: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 746: | Line 746: | ||
=={{header|Gambas}}== |
=={{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. |
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() |
Public Sub Main() |
||
Line 774: | Line 774: | ||
Print "RepeatableTwo" |
Print "RepeatableTwo" |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 785: | Line 785: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 801: | Line 801: | ||
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: |
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) |
applyN n f = foldr (.) id (replicate n f) |
||
main :: IO () |
main :: IO () |
||
main = print $ applyN 10 (\x -> 2 * x) 1</ |
main = print $ applyN 10 (\x -> 2 * x) 1</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1024</pre> |
<pre>1024</pre> |
||
Line 823: | Line 823: | ||
=={{header|Isabelle}}== |
=={{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. |
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 |
imports Main |
||
begin |
begin |
||
Line 877: | Line 877: | ||
lemma "fun_repeat (λ_. a) n = repeat a n" by(induction n) simp+ |
lemma "fun_repeat (λ_. a) n = repeat a n" by(induction n) simp+ |
||
end</ |
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 934: | Line 934: | ||
hi |
hi |
||
hi |
hi |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{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 950: | Line 950: | ||
IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); |
IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 972: | Line 972: | ||
'''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 992: | Line 992: | ||
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 1,006: | Line 1,006: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">function sayHi() |
||
println("Hi") |
println("Hi") |
||
end |
end |
||
Line 1,014: | Line 1,014: | ||
end |
end |
||
rep(sayHi, 3)</ |
rep(sayHi, 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hi |
<pre>Hi |
||
Line 1,021: | Line 1,021: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun repeat(n: Int, f: () -> Unit) { |
fun repeat(n: Int, f: () -> Unit) { |
||
Line 1,032: | Line 1,032: | ||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
repeat(5) { print("Example ") } |
repeat(5) { print("Example ") } |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,047: | Line 1,047: | ||
It runs on Lean 3.4.2: |
It runs on Lean 3.4.2: |
||
< |
<syntaxhighlight lang="lean">def repeat : ℕ → (ℕ → string) → string |
||
| 0 f := "done" |
| 0 f := "done" |
||
| (n + 1) f := (f n) ++ (repeat n f) |
| (n + 1) f := (f n) ++ (repeat n f) |
||
Line 1,053: | Line 1,053: | ||
#eval repeat 5 $ λ b : ℕ , "me " |
#eval repeat 5 $ λ b : ℕ , "me " |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">rep "answer",3 |
||
command rep x,n |
command rep x,n |
||
Line 1,062: | Line 1,062: | ||
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 1,077: | Line 1,077: | ||
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 1,086: | Line 1,086: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{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 1,098: | Line 1,098: | ||
This operator already exists in min and is called <code>times</code>. |
This operator already exists in min and is called <code>times</code>. |
||
{{works with|min|0.19.6}} |
{{works with|min|0.19.6}} |
||
< |
<syntaxhighlight lang="min">("Hello" puts!) 3 times</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,108: | Line 1,108: | ||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">sayHi = function() |
||
print "Hi!" |
print "Hi!" |
||
end function |
end function |
||
Line 1,118: | Line 1,118: | ||
end function |
end function |
||
rep @sayHi, 3</ |
rep @sayHi, 3</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hi! |
<pre>Hi! |
||
Line 1,126: | Line 1,126: | ||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>1 П4 |
<syntaxhighlight lang="text">1 П4 |
||
3 ^ 1 6 ПП 09 С/П |
3 ^ 1 6 ПП 09 С/П |
||
Line 1,132: | Line 1,132: | ||
П7 <-> П0 КПП7 L0 12 В/О |
П7 <-> П0 КПП7 L0 12 В/О |
||
ИП4 С/П КИП4 В/О</ |
ИП4 С/П КИП4 В/О</syntaxhighlight> |
||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE Repeat; |
||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
||
Line 1,158: | Line 1,158: | ||
ReadChar |
ReadChar |
||
END Repeat.</ |
END Repeat.</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="nanoquery">def repeat(f,n) |
||
for i in range(1, n) |
for i in range(1, n) |
||
f() |
f() |
||
Line 1,172: | Line 1,172: | ||
end |
end |
||
repeat(procedure, 3)</ |
repeat(procedure, 3)</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">proc example = |
||
echo "Example" |
echo "Example" |
||
Line 1,209: | Line 1,209: | ||
repeatMacro 4: |
repeatMacro 4: |
||
example() |
example() |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">class Repeat { |
||
function : Main(args : String[]) ~ Nil { |
function : Main(args : String[]) ~ Nil { |
||
Repeat(Example() ~ Nil, 3); |
Repeat(Example() ~ Nil, 3); |
||
Line 1,227: | Line 1,227: | ||
"Example"->PrintLine(); |
"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 1,241: | Line 1,241: | ||
let () = |
let () = |
||
repeat ~n:4 ~f:func |
repeat ~n:4 ~f:func |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 1,247: | Line 1,247: | ||
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 1,265: | Line 1,265: | ||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
; sample function |
; sample function |
||
(define (function) (display "+")) |
(define (function) (display "+")) |
||
Line 1,282: | Line 1,282: | ||
(print) ; print newline |
(print) ; print newline |
||
; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">program Repeater; |
||
type |
type |
||
Line 1,311: | Line 1,311: | ||
begin |
begin |
||
Iterate(P, 3); |
Iterate(P, 3); |
||
end. </ |
end. </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Iteration 1 |
<pre>Iteration 1 |
||
Line 1,321: | Line 1,321: | ||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="perl">sub repeat { |
||
my ($sub, $n) = @_; |
my ($sub, $n) = @_; |
||
$sub->() for 1..$n; |
$sub->() for 1..$n; |
||
Line 1,330: | Line 1,330: | ||
} |
} |
||
repeat(\&example, 4);</ |
repeat(\&example, 4);</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{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;">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: #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,345: | Line 1,345: | ||
<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> |
<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}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang="phixmonti">def myFunc |
||
"Sure looks like a function in here..." print nl |
"Sure looks like a function in here..." print nl |
||
enddef |
enddef |
||
Line 1,360: | Line 1,360: | ||
getid myFunc 4 rep |
getid myFunc 4 rep |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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 1,375: | Line 1,375: | ||
(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 1,394: | Line 1,394: | ||
Step-Function Out-Example -Repeat 3 |
Step-Function Out-Example -Repeat 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,404: | Line 1,404: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog">repeat(_, 0). |
||
repeat(Callable, Times) :- |
repeat(Callable, Times) :- |
||
succ(TimesLess1, Times), |
succ(TimesLess1, Times), |
||
Line 1,411: | Line 1,411: | ||
test :- write('Hello, World'), nl. |
test :- write('Hello, World'), nl. |
||
test(Name) :- format('Hello, ~w~n', Name).</ |
test(Name) :- format('Hello, ~w~n', Name).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,430: | Line 1,430: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Prototype.i fun(x.i) |
||
Procedure.i quark(z.i) |
Procedure.i quark(z.i) |
||
Line 1,440: | Line 1,440: | ||
EndProcedure |
EndProcedure |
||
rep(@quark(),3)</ |
rep(@quark(),3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Quark 3 |
<pre>Quark 3 |
||
Line 1,449: | Line 1,449: | ||
===Procedural=== |
===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 1,457: | Line 1,457: | ||
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=== |
===Functional=== |
||
Repeated function application: |
Repeated function application: |
||
{{Works with|Python|3.7}} |
{{Works with|Python|3.7}} |
||
< |
<syntaxhighlight lang="python">'''Application of a given function, repeated N times''' |
||
from itertools import repeat |
from itertools import repeat |
||
Line 1,560: | Line 1,560: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Application of a given function, repeated N times: |
<pre>Application of a given function, repeated N times: |
||
Line 1,586: | Line 1,586: | ||
The word ''rosetta-times'' is also defined here, using ''times''. It takes both the repeat number and the function as stack arguments. |
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 |
protect times.start |
||
Line 1,618: | Line 1,618: | ||
[ nested ' times nested |
[ nested ' times nested |
||
swap join do ] is rosetta-times ( n x --> )</ |
swap join do ] is rosetta-times ( n x --> )</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,634: | Line 1,634: | ||
=={{header|R}}== |
=={{header|R}}== |
||
<syntaxhighlight lang="r"> |
|||
<lang R> |
|||
f1 <- function(...){print("coucou")} |
f1 <- function(...){print("coucou")} |
||
Line 1,642: | Line 1,642: | ||
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 1,658: | Line 1,658: | ||
(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> |
||
Line 1,665: | Line 1,665: | ||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>sub repeat (&f, $n) { f() xx $n }; |
||
sub example { say rand } |
sub example { say rand } |
||
repeat(&example, 3);</ |
repeat(&example, 3);</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,690: | Line 1,690: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="rebol">Red[] |
||
myrepeat: function [fn n] [loop n [do fn]] |
myrepeat: function [fn n] [loop n [do fn]] |
||
myrepeat [print "hello"] 3</ |
myrepeat [print "hello"] 3</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,705: | Line 1,705: | ||
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 #= 1 /*assume once if not specified. */ |
if #=='' | #=="," then #= 1 /*assume once if not specified. */ |
||
Line 1,715: | Line 1,715: | ||
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>}} |
{{out|output|text= when using the input of: <tt> yabba 4 </tt>}} |
||
<pre> |
<pre> |
||
Line 1,733: | Line 1,733: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
Func Main |
Func Main |
||
times(5,:test) |
times(5,:test) |
||
Line 1,744: | Line 1,744: | ||
Call F() |
Call F() |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">4.times{ puts "Example" } # idiomatic way |
||
def repeat(proc,num) |
def repeat(proc,num) |
||
Line 1,753: | Line 1,753: | ||
end |
end |
||
repeat(->{ puts "Example" }, 4)</ |
repeat(->{ puts "Example" }, 4)</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
Line 1,759: | Line 1,759: | ||
Rust has higher-order functions. |
Rust has higher-order functions. |
||
< |
<syntaxhighlight lang="rust">fn repeat(f: impl FnMut(usize), n: usize) { |
||
(0..n).for_each(f); |
(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. |
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,769: | Line 1,769: | ||
It's idiomatic to use a closure. |
It's idiomatic to use a closure. |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
repeat(|x| print!("{};", x), 5); |
repeat(|x| print!("{};", x), 5); |
||
}</ |
}</syntaxhighlight> |
||
{{out}}<pre>0;1;2;3;4;</pre> |
{{out}}<pre>0;1;2;3;4;</pre> |
||
Line 1,778: | Line 1,778: | ||
Also possible to define a static function. |
Also possible to define a static function. |
||
< |
<syntaxhighlight lang="rust">fn function(x: usize) { |
||
print!("{};", x); |
print!("{};", x); |
||
} |
} |
||
Line 1,784: | Line 1,784: | ||
fn main() { |
fn main() { |
||
repeat(function, 4); |
repeat(function, 4); |
||
}</ |
}</syntaxhighlight> |
||
{{out}}<pre>0;1;2;3;</pre> |
{{out}}<pre>0;1;2;3;</pre> |
||
Line 1,792: | Line 1,792: | ||
Sometimes it may be convenient to call a static method. |
Sometimes it may be convenient to call a static method. |
||
< |
<syntaxhighlight lang="rust">struct Foo; |
||
impl Foo { |
impl Foo { |
||
fn associated(x: usize) { |
fn associated(x: usize) { |
||
Line 1,801: | Line 1,801: | ||
fn main() { |
fn main() { |
||
repeat(Foo::associated, 8); |
repeat(Foo::associated, 8); |
||
}</ |
}</syntaxhighlight> |
||
{{out}}<pre>0;1;2;3;4;5;6;7;</pre> |
{{out}}<pre>0;1;2;3;4;5;6;7;</pre> |
||
Line 1,808: | Line 1,808: | ||
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>. |
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); |
fn run(self); |
||
} |
} |
||
Line 1,820: | Line 1,820: | ||
fn main() { |
fn main() { |
||
repeat(Bar::run, 6); |
repeat(Bar::run, 6); |
||
}</ |
}</syntaxhighlight> |
||
{{out}}<pre>0;1;2;3;4;5;</pre> |
{{out}}<pre>0;1;2;3;4;5;</pre> |
||
Line 1,827: | Line 1,827: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="rust">fn repeat(f: impl FnMut(usize), n: usize) { |
||
(0..n).for_each(f); |
(0..n).for_each(f); |
||
} |
} |
||
Line 1,837: | Line 1,837: | ||
mult += x; |
mult += x; |
||
}, 5); |
}, 5); |
||
}</ |
}</syntaxhighlight> |
||
{{out}}<pre>0;1;4;12;28;</pre> |
{{out}}<pre>0;1;4;12;28;</pre> |
||
Line 1,845: | Line 1,845: | ||
# 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 1,854: | Line 1,854: | ||
# 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 1,869: | Line 1,869: | ||
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 1,878: | Line 1,878: | ||
# Infix notation |
# Infix notation |
||
# Operator overloading |
# Operator overloading |
||
< |
<syntaxhighlight lang="scala">import scala.annotation.tailrec |
||
object Repeat3 extends App { |
object Repeat3 extends App { |
||
Line 1,895: | Line 1,895: | ||
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}}== |
=={{header|Scheme}}== |
||
Line 1,902: | Line 1,902: | ||
an unspecified value. The actual value returned varies depending on the Scheme implementation itself. |
an unspecified value. The actual value returned varies depending on the Scheme implementation itself. |
||
< |
<syntaxhighlight lang="scheme"> |
||
(import (scheme base) |
(import (scheme base) |
||
(scheme write)) |
(scheme write)) |
||
Line 1,916: | Line 1,916: | ||
;; example returning a number |
;; example returning a number |
||
(display (repeat (lambda () (+ 1 2)) 5)) (newline) |
(display (repeat (lambda () (+ 1 2)) 5)) (newline) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,931: | Line 1,931: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: myRepeat (in integer: times, in proc: aProcedure) is func |
const proc: myRepeat (in integer: times, in proc: aProcedure) is func |
||
Line 1,945: | Line 1,945: | ||
begin |
begin |
||
myRepeat(3, writeln("Hello!")); |
myRepeat(3, writeln("Hello!")); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,954: | Line 1,954: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func repeat(f, n) { |
||
{ f() } * n; |
{ f() } * n; |
||
} |
} |
||
Line 1,962: | Line 1,962: | ||
} |
} |
||
repeat(example, 4);</ |
repeat(example, 4);</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">fun repeat (_, 0) = () |
||
| repeat (f, n) = (f (); repeat (f, n - 1)) |
| repeat (f, n) = (f (); repeat (f, n - 1)) |
||
Line 1,971: | Line 1,971: | ||
print "test\n" |
print "test\n" |
||
val () = repeat (testProcedure, 5)</ |
val () = repeat (testProcedure, 5)</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">function repeat(f,n) { |
||
for (i=1; i<=n; i++) (*f)() |
for (i=1; i<=n; i++) (*f)() |
||
} |
} |
||
Line 1,983: | Line 1,983: | ||
} |
} |
||
repeat(&hello(),3)</ |
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 1,992: | Line 1,992: | ||
} |
} |
||
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 2,003: | Line 2,003: | ||
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}}== |
=={{header|uBasic/4tH}}== |
||
<lang>Proc _Repeat (_HelloWorld, 5) : End |
<syntaxhighlight lang="text">Proc _Repeat (_HelloWorld, 5) : End |
||
_Repeat Param (2) : Local (1) : For c@ = 1 To b@ : Proc a@ : Next : Return |
_Repeat Param (2) : Local (1) : For c@ = 1 To b@ : Proc a@ : Next : Return |
||
_HelloWorld Print "Hello world!" : Return</ |
_HelloWorld Print "Hello world!" : Return</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,026: | Line 2,026: | ||
=={{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 2,037: | Line 2,037: | ||
# outputs "Hello! " 5 times |
# outputs "Hello! " 5 times |
||
repeat procedure 5</ |
repeat procedure 5</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
{{trans|Phix}}< |
{{trans|Phix}}<syntaxhighlight lang="vb">Private Sub Repeat(rid As String, n As Integer) |
||
For i = 1 To n |
For i = 1 To n |
||
Application.Run rid |
Application.Run rid |
||
Line 2,052: | Line 2,052: | ||
Public Sub main() |
Public Sub main() |
||
Repeat "Hello", 5 |
Repeat "Hello", 5 |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
=={{header|Verilog}}== |
=={{header|Verilog}}== |
||
< |
<syntaxhighlight lang="verilog">module main; |
||
initial begin |
initial begin |
||
repeat(5) begin |
repeat(5) begin |
||
Line 2,062: | Line 2,062: | ||
$display("Loop Ended"); |
$display("Loop Ended"); |
||
end |
end |
||
endmodule</ |
endmodule</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Inside loop |
<pre>Inside loop |
||
Line 2,073: | Line 2,073: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="vbnet">Module Module1 |
||
Sub Repeat(count As Integer, fn As Action(Of Integer)) |
Sub Repeat(count As Integer, fn As Action(Of Integer)) |
||
Line 2,089: | Line 2,089: | ||
End Sub |
End Sub |
||
End Module</ |
End Module</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Example 1 |
<pre>Example 1 |
||
Line 2,096: | Line 2,096: | ||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang="vlang">fn repeat(n int, f fn()) { |
||
for _ in 0.. n { |
for _ in 0.. n { |
||
f() |
f() |
||
Line 2,108: | Line 2,108: | ||
fn main() { |
fn main() { |
||
repeat(4, func) |
repeat(4, func) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Example |
<pre>Example |
||
Line 2,117: | Line 2,117: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="ecmascript">var f = Fn.new { |g, n| |
||
for (i in 1..n) g.call(n) |
for (i in 1..n) g.call(n) |
||
} |
} |
||
Line 2,126: | Line 2,126: | ||
} |
} |
||
f.call(g, 5)</ |
f.call(g, 5)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,139: | Line 2,139: | ||
=={{header|XBS}}== |
=={{header|XBS}}== |
||
XBS has a built-in repeat keyword. |
XBS has a built-in repeat keyword. |
||
< |
<syntaxhighlight lang="xbs">func rep(callback:function,amount:number,*args:array=[]):null{ |
||
repeat amount { |
repeat amount { |
||
callback(*args); |
callback(*args); |
||
Line 2,147: | Line 2,147: | ||
rep(func(a,b,c){ |
rep(func(a,b,c){ |
||
log(a+b+c); |
log(a+b+c); |
||
},3,1,2,3);</ |
},3,1,2,3);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,156: | Line 2,156: | ||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
< |
<syntaxhighlight lang="lisp">(defun repeat (f n) |
||
(f) |
(f) |
||
(if (> n 1) |
(if (> n 1) |
||
Line 2,162: | Line 2,162: | ||
;; an example to test it: |
;; an example to test it: |
||
(repeat (lambda () (print '(hello rosetta code))) 5)</ |
(repeat (lambda () (print '(hello rosetta code))) 5)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(HELLO ROSETTA CODE) |
<pre>(HELLO ROSETTA CODE) |
||
Line 2,172: | Line 2,172: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
{{trans|Lua}} |
{{trans|Lua}} |
||
< |
<syntaxhighlight lang="yabasic">sub myFunc () |
||
print "Sure looks like a function in here..." |
print "Sure looks like a function in here..." |
||
end sub |
end sub |
||
Line 2,182: | Line 2,182: | ||
end sub |
end sub |
||
rep("myFunc", 4)</ |
rep("myFunc", 4)</syntaxhighlight> |
||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |
||
Line 2,188: | Line 2,188: | ||
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. |
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 b,&05 ;load the decrement value into b |
||
ld hl,myFunc ;load the address of "myFunc" into HL |
ld hl,myFunc ;load the address of "myFunc" into HL |
||
Line 2,215: | Line 2,215: | ||
pop hl |
pop hl |
||
ret |
ret |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== Indirect Jump === |
=== Indirect Jump === |
||
Same as above but uses an indirect jump to the address in HL. |
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".</ |
jp (hl) ;despite the parentheses this does NOT dereference HL, it merely acts as "LD PC,HL".</syntaxhighlight> |
||
===Using self-modifying code=== |
===Using self-modifying code=== |
||
Line 2,234: | Line 2,234: | ||
call &0000 ;gets overwritten with the address of MyFunc |
call &0000 ;gets overwritten with the address of MyFunc |
||
djnz repeatProc |
djnz repeatProc |
||
ret</ |
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> |