I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

# Repeat

Repeat
You are encouraged to solve this task according to the task description, using any language you may know.

Write a procedure which accepts as arguments another procedure and a positive integer.

The latter procedure is executed a number of times equal to the accepted integer.

`with Ada.Text_IO; procedure Repeat_Example is    procedure Repeat(P: access Procedure; Reps: Natural) is   begin      for I in 1 .. Reps loop	 P.all; -- P points to a procedure, and P.all actually calls that procedure      end loop;   end Repeat;    procedure Hello is   begin      Ada.Text_IO.Put("Hello! ");   end Hello; begin   Repeat(Hello'Access, 3); -- Hello'Access points to the procedure Helloend Repeat_Example;`

Output:

`Hello! Hello! Hello! `

## ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.win32
` # operator that executes a procedure the specified number of times            #OP REPEAT = ( INT count, PROC VOID routine )VOID:    TO count DO routine OD; # make REPEAT a low priority operater                                         #PRIO REPEAT = 1;  # can also create variant that passes the iteration count as a parameter      #OP REPEAT = ( INT count, PROC( INT )VOID routine )VOID:    FOR iteration TO count DO routine( iteration ) OD; main: (     # PROC to test the REPEAT operator with                                   #    PROC say something = VOID: print( ( "something", newline ) );     3 REPEAT say something;     # PROC to test the variant                                                #    PROC show squares = ( INT n )VOID: print( ( n, n * n, newline ) );     3 REPEAT show squares ) `

Output:

```something
something
something
+1         +1
+2         +4
+3         +9
```

## AppleScript

`-- applyN :: Int -> (a -> a) -> a -> aon applyN(n, f, x)    script go        on |λ|(a, g)            |λ|(a) of mReturn(g)        end |λ|    end script    foldl(go, x, replicate(n, f))end applyN  -------- SAMPLE FUNCTIONS FOR REPEATED APPLICATION -------- on double(x)    2 * xend double  on plusArrow(s)    s & " -> "end plusArrow  on squareRoot(n)    n ^ 0.5end squareRoot -------------------------- TESTS --------------------------on run    log applyN(10, double, 1)    --> 1024     log applyN(5, plusArrow, "")    --> " ->  ->  ->  ->  -> "     log applyN(3, squareRoot, 65536)    --> 4.0end run  -------------------- GENERIC FUNCTIONS -------------------- -- foldl :: (a -> b -> a) -> a -> [b] -> aon foldl(f, startValue, xs)    tell mReturn(f)        set v to startValue        set lng to length of xs        repeat with i from 1 to lng            set v to |λ|(v, item i of xs, i, xs)        end repeat        return v    end tellend foldl  -- mReturn :: First-class m => (a -> b) -> m (a -> b)on mReturn(f)    -- 2nd class handler function lifted into 1st class script wrapper.     if script is class of f then        f    else        script            property |λ| : f        end script    end ifend mReturn -- Egyptian multiplication - progressively doubling a list, appending-- stages of doubling to an accumulator where needed for binary -- assembly of a target length-- replicate :: Int -> a -> [a]on replicate(n, a)    set out to {}    if 1 > n then return out    set dbl to {a}     repeat while (1 < n)        if 0 < (n mod 2) then set out to out & dbl        set n to (n div 2)        set dbl to (dbl & dbl)    end repeat    return out & dblend replicate`
Output:
```(*1024*)
(* ->  ->  ->  ->  -> *)
(*4.0*)```

## Arturo

`proc: {	print "I'm in proc!"} repeat: @(func times){	loop times {		func ~	}} repeat proc 3`
Output:
```I'm in proc!
I'm in proc!
I'm in proc!```

## AutoHotkey

`repeat("fMsgBox",3)return repeat(f, n){	loop % n		%f%()} fMsgBox(){	MsgBox hello}`

## AWK

` # syntax: GAWK -f REPEAT.AWKBEGIN {    for (i=0; i<=3; i++) {      f = (i % 2 == 0) ? "even" : "odd"      @f(i) # indirect function call    }    exit(0)}function even(n,  i) {    for (i=1; i<=n; i++) {      printf("inside even %d\n",n)    }}function odd(n,  i) {    for (i=1; i<=n; i++) {      printf("inside odd %d\n",n)    }} `

output:

```inside odd 1
inside even 2
inside even 2
inside odd 3
inside odd 3
inside odd 3
```

## Batch File

` @echo off :_mainsetlocalcall:_func1 _func2 3pause>nulexit/b :_func1setlocal enabledelayedexpansionfor /l %%i in (1,1,%2) do call:%1exit /b :_func2setlocalecho _func2 has been executedexit /b `

## C

`#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0)  (*f)(); //or just f()} void example() { printf("Example\n");} int main(int argc, char *argv[]) { repeat(example, 4); return 0;} `

## C#

Translation of: Java
`using System; namespace Repeat {    class Program {        static void Repeat(int count, Action<int> fn) {            if (null == fn) {                throw new ArgumentNullException("fn");            }            for (int i = 0; i < count; i++) {                fn.Invoke(i + 1);            }        }         static void Main(string[] args) {            Repeat(3, x => Console.WriteLine("Example {0}", x));        }    }}`
Output:
```Example 1
Example 2
Example 3```

## C++

`template <typename Function>void repeat(Function f, unsigned int n) { for(unsigned int i=n; 0<i; i--)  f();}`

usage:

`#include <iostream>void example() { std::cout << "Example\n";} repeat(example, 4);`
Works with: C++11
` repeat([]{std::cout << "Example\n";}, 4);`

## Clojure

`(defn repeat-function [f n]   (dotimes [i n] (f)))`
Output:
```user=> (repeat-function #(println "bork") 3)
bork
bork
bork```

## Common Lisp

`(defun repeat (f n)  (dotimes (i n) (funcall f))) (repeat (lambda () (format T "Example~%")) 5)`

## D

`void repeat(void function() fun, in uint times) {    foreach (immutable _; 0 .. times)        fun();} void procedure() {    import std.stdio;    "Example".writeln;} void main() {    repeat(&procedure, 3);}`
Output:
```Example
Example
Example```

## Delphi

` program Repeater; {\$APPTYPE CONSOLE}{\$R *.res} type  TSimpleProc = procedure;     // Can also define types for procedures (& functions) which                               // require params. procedure Once;begin  writeln('Hello World');end; procedure Iterate(proc : TSimpleProc; Iterations : integer);var  i : integer;begin  for i := 1 to Iterations do    proc;end; begin  Iterate(Once, 3);  readln;end.  `
Output:
```Hello World
Hello World
Hello World```

## EchoLisp

` (define (repeat f n) (for ((i n)) (f))) (repeat (lambda () (write (random 1000))) 5)    → 287 798 930 989 794  ;; Remark;; It is also possible to iterate a function : f(f(f(f( ..(f x)))))(define cos10 (iterate cos 10)(define cos100 (iterate cos10 10))(cos100 0.6)    →  0.7390851332151605(cos 0.7390851332151605)    → 0.7390851332151608 ;; fixed point found `

## F#

`open System let Repeat c f =    for _ in 1 .. c do        f() let Hello _ =     printfn "Hello world" [<EntryPoint>]let main _ =    Repeat 3 Hello     0 // return an integer exit code`

## Factor

Factor comes with the times word which does exactly this. For example,

`3 [ "Hello!" print ] times`
Output:
```Hello!
Hello!
Hello!
```

The implementation of times:

`: times ( ... n quot: ( ... -- ... ) -- ... )    [ drop ] prepose each-integer ; inline`

## Forth

`: times ( xt n -- )  0 ?do dup execute loop drop ;`

Or, taking care to keep the data stack clean for the XT's use, as is often desired:

`: times { xt n -- }  n 0 ?do xt execute loop ;`

Or as a novel control structure, which is not demanded by this task but which is just as idiomatic in Forth as the XT-consuming alternatives above:

`: times[  ]] 0 ?do [[ ; immediate compile-only: ]times  postpone loop ;  immediate compile-only`

Usage:

`[: cr ." Hello" ;] 3 times : 3-byes ( -- )  3 times[ cr ." Bye" ]times ;3-byes`
Output:
```Hello
Hello
Hello
Bye
Bye

Bye```

## FreeBASIC

`' FB 1.05.0 Win64 Sub proc()  Print " proc called"End Sub Sub repeat(s As Sub, n As UInteger)  For i As Integer = 1 To n    Print Using "##"; i;    s()  NextEnd Sub repeat(@proc, 5)PrintPrint "Press any key to quit"Sleep`
Output:
``` 1 proc called
2 proc called
3 proc called
4 proc called
5 proc called
```

## Gambas

Note: Gambas (3.14.0) cannot perform this task as specified, as it does not have delegates, and pointers do not seem to work with procedures. What does work is using Object.Call, which is intended for executing procedures from external libraries. However the accepting procedure must refer to the object containing the procedure, and refer to the procedure by a String name. In this case, the current module/class reference (Me) is used, but the String name must be passed. This arrangement will only work within the same module/class. It may be possible to pass the parent reference to a method (taking 3 parameters) in another class if the named procedure is Public. The empty array ([]) in Object.Call represent a procedure without parameters, which are not an explicit requirement for this Task, but might require another parameter to the accepting procedure.

` Public Sub Main()     RepeatIt("RepeatableOne", 2)     RepeatIt("RepeatableTwo", 3) End 'Cannot pass procedure pointer in Gambas; must pass procedure name and use Object.Call()Public Sub RepeatIt(sDelegateName As String, iCount As Integer)     For iCounter As Integer = 1 To iCount        Object.Call(Me, sDelegateName, [])    Next End Public Sub RepeatableOne()     Print "RepeatableOne" End Public Sub RepeatableTwo()     Print "RepeatableTwo" End`

Output:

```RepeatableOne
RepeatableOne
RepeatableTwo
RepeatableTwo
RepeatableTwo
```

## Go

`package main import "fmt" func repeat(n int, f func()) {  for i := 0; i < n; i++ {    f()  }} func fn() {  fmt.Println("Example")} func main() {  repeat(4, fn)}`

`import Control.Monad (replicateM_) sampleFunction :: IO ()sampleFunction = putStrLn "a" main = replicateM_ 5 sampleFunction`

And if the requirement is for something like a Church numeral, compounding the application of a given function n times (rather than repeating the same IO event n times) then we could also write something like applyN below:

`applyN :: Int -> (a -> a) -> a -> aapplyN n f = foldr (.) id (replicate n f) main :: IO ()main = print \$ applyN 10 (\x -> 2 * x) 1`
Output:
`1024`

## J

`    NB. ^: (J's power conjunction) repeatedly evaluates a verb.    NB. Appending to a vector the sum of the most recent   NB. 2 items can generate the Fibonacci sequence.    (, [: +/ _2&{.)  (^:4)  0 10 1 1 2 3 5     NB. Repeat an infinite number of times   NB. computes the stable point at convergence    cosine =: 2&o.    cosine (^:_ ) 2    NB. 2 is the initial value0.739085    cosine 0.739085  NB. demonstrate the stable point x==Cos(x)0.739085     cosine^:(<_) 2  NB. show the convergence2 _0.416147 0.914653 0.610065 0.819611 0.682506 0.775995 0.713725 0.755929 0.727635 0.74675 0.733901 0.742568 0.736735 0.740666 0.738019 0.739803 0.738602 0.739411 0.738866 0.739233 0.738986 0.739152 0.73904 0.739116 0.739065 0.739099 0.739076 0.739091 0.7...     # cosine^:(<_) 2  NB. iteration tallyft78    f =: 3 :'smoutput ''hi'''    f''hi    NB. pass verbs via a gerund   repeat =: dyad def 'for_i. i.y do. (x`:0)0 end. EMPTY'    (f`'')repeat 4hihihihi      NB. pass a verb directly to an adverb    Repeat =: adverb def 'for_i. i.y do. u 0 end. EMPTY'    f Repeat 4hihihihi `

## Java

Works with: Java version 8
`import java.util.function.Consumer;import java.util.stream.IntStream; public class Repeat {     public static void main(String[] args) {        repeat(3, (x) -> System.out.println("Example " + x));    }     static void repeat (int n, Consumer<Integer> fun) {        IntStream.range(0, n).forEach(i -> fun.accept(i + 1));    }}`

Output:

```Example 1
Example 2
Example 3```

## jq

Works with: jq version 1.4

We first define "repeat" naively but in accordance with the task specification; we then define an optimized version that illustrates a general technique for taking advantage of jq's support for tail-call optimization (TCO).

Since jq is a purely functional language, repeat(f; n) is unlikely to be very useful so we define a similar filter, repeatedly(f; n), which generates n+1 terms: . (the input), f, f|f, ... ; that is, using conventional functional notation, it generates: x, f(x), f(f(x)), ...

Unoptimized version:

`def unoptimized_repeat(f; n):  if n <= 0 then empty  else f, repeat(f; n-1)  end;`

Optimized for TCO:

`def repeat(f; n):  # state: [count, in]  def r:    if . >= n then empty else (. | f), (. += 1 | r) end;  [0, .] | r;`

Variant:

`# If n is a non-negative integer,# then emit a stream of (n + 1) terms: ., f, f|f, f|f|f, ...def repeatedly(f; n):  # state: [count, in]  def r:    if . < 0 then empty    else ., ([. - 1, (. | f)] | r)    end;  [n, .] | r;`

Examples:

`0 | [ repeat(.+1; 3) ]`

produces: [1,1,1]

`0 | repeatedly(.+1; 3)`

produces:

```0
1
2
3
```

## Julia

`function sayHi()	println("Hi")end function rep(f, n)	for i = 1:n f() endend rep(sayHi, 3)`
Output:
```Hi
Hi
Hi```

## Kotlin

`// version 1.0.6 fun repeat(n: Int, f: () -> Unit) {    for (i in 1..n) {        f()        println(i)    }} fun main(args: Array<String>) {    repeat(5) { print("Example ") }}`
Output:
```Example 1
Example 2
Example 3
Example 4
Example 5
```

## LiveCode

`rep "answer",3 command rep x,n    repeat n times        do merge("[[x]] [[n]]")    end repeatend rep`

## Lua

No particular magic required as Lua allows functions to be passed as arguments.

`function myFunc ()    print("Sure looks like a function in here...")end function rep (func, times)    for count = 1, times do        func()    endend rep(myFunc, 4) `
Output:
```Sure looks like a function in here...
Sure looks like a function in here...
Sure looks like a function in here...
Sure looks like a function in here...```

## Mathematica

Note that anything of this form is not considered good practice.

`repeat[f_, n_] := Do[f[], {n}];repeat[Print["Hello, world!"] &, 5];`
Output:
```Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!```

## min

This operator already exists in min and is called `times`.

Works with: min version 0.19.6
`("Hello" puts!) 3 times`
Output:
```Hello
Hello
Hello
```

## MiniScript

`sayHi = function()    print "Hi!"end function rep = function(f, n)    for i in range(1, n)        f    end forend function rep @sayHi, 3`
Output:
```Hi!
Hi!
Hi!```

## МК-61/52

`1	П4 3	^	1	6	ПП	09	С/П П7	<->	П0	КПП7	L0	12	В/О ИП4	С/П	КИП4	В/О`

## Modula-2

`MODULE Repeat;FROM Terminal IMPORT WriteString,WriteLn,ReadChar; TYPE F = PROCEDURE; PROCEDURE Repeat(fun : F; c : INTEGER);VAR i : INTEGER;BEGIN    FOR i:=1 TO c DO        fun    ENDEND Repeat; PROCEDURE Print;BEGIN    WriteString("Hello");    WriteLnEND Print; BEGIN    Repeat(Print, 3);     ReadCharEND Repeat.`

## Nanoquery

Translation of: Python
`def repeat(f,n)    for i in range(1, n)        f()    endend def procedure()    println "Example"end repeat(procedure, 3)`

## Objeck

`class Repeat {  function : Main(args : String[]) ~ Nil {    Repeat(Example() ~ Nil, 3);  }   function : Repeat(e : () ~ Nil, i : Int) ~ Nil {    while(i-- > 0) {      e();    };  }   function : Example() ~ Nil {    "Example"->PrintLine();  }}`

## OCaml

`let repeat ~f ~n =  for i = 1 to n do    f ()  done let func () =  print_endline "Example" let () =  repeat ~n:4 ~f:func `

## Oforth

This method is already defined : times. This method can be used on all runnables (functions, methods, blocks, ...).

`: hello "Hello, World!" println ;10 #hello times`
Output:
```Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
```

## Ol

` ; sample function(define (function) (display "+")) ; simple case for 80 times(for-each (lambda (unused) (function)) (iota 80))(print) ; print newline; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ; detailed case for 80 times(let loop ((fnc function) (n 80))   (unless (zero? n)      (begin         (fnc)         (loop fnc (- n 1)))))(print) ; print newline; ==> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ `

## PARI/GP

`repeat(f, n)=for(i=1,n,f());repeat( ()->print("Hi!"), 2);`
Output:
```Hi!
Hi!```

## Perl

Translation of: C
`sub repeat {    my (\$sub, \$n) = @_;    \$sub->() for 1..\$n;} sub example {    print "Example\n";} repeat(\&example, 4);`

## Phix

`procedure Repeat(integer rid, integer n)    for i=1 to n do        call_proc(rid,{})    end forend procedure procedure Hello()    ?"Hello"end procedure Repeat(routine_id("Hello"),5)`

## Phixmonti

`def myFunc    "Sure looks like a function in here..." print nlenddef def rep /# func times -- #/    for drop	dup exec    endfor    dropenddef getid myFunc 4 rep `

## PicoLisp

`# The built-in function "do" can be used to achieve our goal,# however, it has a slightly different syntax than what the# problem specifies. # Native solution.(do 10 (version)) # Our solution.(de dofn (Fn N)   (do N (Fn)) ) (dofn version 10)`

## PowerShell

Translation of: Python
` function Out-Example{    "Example"} function Step-Function ([string]\$Function, [int]\$Repeat){    for (\$i = 1; \$i -le \$Repeat; \$i++)    {         "\$(Invoke-Expression -Command \$Function) \$i"    }} Step-Function Out-Example -Repeat 3 `
Output:
```Example 1
Example 2
Example 3
```

## Prolog

`repeat(_, 0).repeat(Callable, Times) :-	succ(TimesLess1, Times),	Callable,	repeat(Callable, TimesLess1). test :- write('Hello, World'), nl.	test(Name) :- format('Hello, ~w~n', Name).`
Output:
```?- repeat(test, 3).
Hello, World
Hello, World
Hello, World
true ;
false.

?- repeat(test('Fred'), 3).
Hello, Fred
Hello, Fred
Hello, Fred
true ;
false.
```

## Python

### Procedural

`#!/usr/bin/pythondef repeat(f,n):  for i in range(n):    f(); def procedure():  print("Example"); repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.`

### Functional

Repeated function application:

Works with: Python version 3.7
`'''Application of a given function, repeated N times''' from itertools import repeatfrom functools import reducefrom inspect import getsource  # applyN :: Int -> (a -> a) -> a -> adef applyN(n):    '''n compounding applications of the supplied       function f. Equivalent to Church numeral n.    '''    def go(f):        return lambda x: reduce(            lambda a, g: g(a), repeat(f, n), x        )    return lambda f: go(f)  # MAIN ----------------------------------------------------def main():    '''Tests - compounding repetition       of function application.    '''    def f(x):        return x + 'Example\n'     def g(x):        return 2 * x     def h(x):        return 1.05 * x     print(        fTable(__doc__ + ':')(            lambda fx: '\nRepeated * 3:\n (' + (                getsource(fst(fx)).strip() + ')(' +                repr(snd(fx)) + ')'            )        )(str)(            liftA2(applyN(3))(fst)(snd)        )([(f, '\n'), (g, 1), (h, 100)])    )  # GENERIC ------------------------------------------------- # compose (<<<) :: (b -> c) -> (a -> b) -> a -> cdef compose(g):    '''Right to left function composition.'''    return lambda f: lambda x: g(f(x))  # fst :: (a, b) -> adef fst(tpl):    '''First member of a pair.'''    return tpl  # liftA2 :: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> cdef liftA2(op):    '''Lift a binary function to a composition       over two other functions.       liftA2 (*) (+ 2) (+ 3) 7 == 90    '''    def go(f, g):        return lambda x: op(            f(x)        )(g(x))    return lambda f: lambda g: go(f, g)  # snd :: (a, b) -> bdef snd(tpl):    '''Second member of a pair.'''    return tpl  # fTable :: String -> (a -> String) ->#                     (b -> String) -> (a -> b) -> [a] -> Stringdef fTable(s):    '''Heading -> x display function -> fx display function ->                     f -> xs -> tabular string.    '''    def go(xShow, fxShow, f, xs):        ys = [xShow(x) for x in xs]        w = max(map(len, ys))        return s + '\n' + '\n'.join(map(            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),            xs, ys        ))    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(        xShow, fxShow, f, xs    )  # MAIN ---if __name__ == '__main__':    main()`
Output:
```Application of a given function, repeated N times:

Repeated * 3:
(def f(x):
return x + 'Example\n')('\n') ->
Example
Example
Example

Repeated * 3:
(def g(x):
return 2 * x)(1) -> 8

Repeated * 3:
(def h(x):
return 1.05 * x)(100) -> 115.7625```

## R

` f1 <- function(...){print("coucou")} f2 <-function(f,n){lapply(seq_len(n),eval(f))} f2(f1,4) `

## Racket

The racket guide has a section called "Iterators and Comprehensions", which shows that for isn't just for repeating n times!

`#lang racket/base(define (repeat f n) ; the for loop is idiomatic of (although not exclusive to) racket  (for ((_ n)) (f))) (define (repeat2 f n) ; This is a bit more "functional programmingy"  (when (positive? n) (f) (repeat2 f (sub1 n)))) (display "...")(repeat (λ () (display " and over")) 5)(display "...")(repeat2 (λ () (display " & over")) 5)(newline)`
Output:
`... and over and over and over and over and over... & over & over & over & over & over`

## Raku

(formerly Perl 6)

`sub repeat (&f, \$n) { f() xx \$n }; sub example { say rand } repeat(&example, 3);`
Output:
```0.435249779778396
0.647701200726486
0.279289335968417
```
Of course, we could have just written
`example() xx 3;`
or even
`(say rand) xx 3;`
directly – the custom `repeat` subroutine is just here to satisfy the task description.

Notes on the `xx` operator:

• Unlike other operators, it evaluates its left-hand-side argument lazily - that's why we can simply call `f()` there rather than passing it as a function object.
• The operator has a return value: A list consisting of the return values of the left-hand-side (and building lists is in fact what `xx` is usually used for).

General notes:

• The `&` sigil in the `repeat` subroutine signature restricts that parameter to types that implement the `Callable` role, and makes it available inside the `repeat` subroutine body as if it were a lexically scoped sub.
• The parentheses in the last line are necessary to disambiguate it as a call to our custom subroutine, rather than an attempt to use the built-in `repeat { ... } while ...` construct.

## REXX

The procedure name (that is being repeatedly executed) isn't restricted to an   internal   REXX subroutine (procedure),
it may be an   external   program (procedure) written in any language.

`/*REXX program   executes   a  named procedure  a specified number of times.            */parse arg pN # .                                 /*obtain optional arguments from the CL*/if #=='' | #==","   then #=1                     /*assume  once  if not specified.      */if pN\==''          then call repeats pN, #      /*invoke the REPEATS procedure for  pN.*/exit                                             /*stick a fork in it,  we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/repeats: procedure;  parse arg x,n               /*obtain the procedureName & # of times*/                do n;  interpret 'CALL' x;  end  /*repeat the invocation    N    times. */         return                                  /*return to invoker of the REPEATS proc*//*──────────────────────────────────────────────────────────────────────────────────────*/yabba:   say 'Yabba, yabba do!';          return /*simple code;  no need for  PROCEDURE.*/`

output when the input is:   yabba 4

```Yabba, yabba do!
Yabba, yabba do!
Yabba, yabba do!
Yabba, yabba do!
```

output when the input is:   \$date 3

[The (external)   \$DATE.REX   program isn't supplied here.]

```day-of-year= 159                Gregorian date= 06/08/2014               Sunday
day-of-year= 159                Gregorian date= 06/08/2014               Sunday
day-of-year= 159                Gregorian date= 06/08/2014               Sunday
```

## Ring

` Func Main     times(5,:test) Func Test     see "Message from the test function!" + nl Func Times nCount, F     for x = 1 to nCount         Call F()     next `

## Ruby

`4.times{ puts "Example" }  # idiomatic way def repeat(proc,num)  num.times{ proc.call }end repeat(->{ puts "Example" }, 4)`

## Rust

Rust has higher-order functions.

`fn repeat(f: impl FnMut(usize), n: usize) {    (0..n).for_each(f);}`

Here we define the function `repeat` which takes the function `Fn(usize)`, which is an anonymous trait constraint by the `impl Trait` syntax, in such a way that it's size can be known statically at compile time. The range iterator `0..n` is used, in combination with the `Iterator::for_each` method to consume it.

### Closure

It's idiomatic to use a closure.

`fn main() {    repeat(|x| print!("{};", x), 5);}`
Output:
`0;1;2;3;4;`

### Static Function

Also possible to define a static function.

`fn function(x: usize) {    print!("{};", x);} fn main() {    repeat(function, 4);}`
Output:
`0;1;2;3;`

### Static Method

Sometimes it may be convenient to call a static method.

`struct Foo;impl Foo {    fn associated(x: usize) {        print!("{};", x);    }} fn main() {    repeat(Foo::associated, 8);}`
Output:
`0;1;2;3;4;5;6;7;`

### Trait Method

You can also use implemented trait-methods as a function-argument. This works because the implemented type is `usize` which is what the iterator supplied to `Fn(usize)`.

`trait Bar {    fn run(self);} impl Bar for usize {    fn run(self) {        print!("{};", self);    }} fn main() {    repeat(Bar::run, 6);}`
Output:
`0;1;2;3;4;5;`

### Mutable Closure

The most interesting application would probably be a mutable closure, which requires changing the type signature from `Fn` to `FnMut`, because they are constrained by slightly different rules, but otherwise work the same.

`fn repeat(f: impl FnMut(usize), n: usize) {    (0..n).for_each(f);} fn main() {    let mut mult = 1;    repeat(|x| {        print!("{};", x * mult);        mult += x;    }, 5);}`
Output:
`0;1;4;12;28;`

## Scala

### Intuitive solution

1. Call by name
2. Type parameterization
3. Higher order function
`  def repeat[A](n:Int)(f: => A)= ( 0 until n).foreach(_ => f)   repeat(3) { println("Example") }`

1. Call by name
2. Type parameterization
3. Implicit method
4. Tail recursion
5. Infix notation
`object Repeat2 extends App {    implicit class IntWithTimes(x: Int) {      def times[A](f: => A):Unit = {    @tailrec      def loop( current: Int): Unit =        if (current > 0) {          f          loop(current - 1)        }      loop(x)    }  }   5 times println("ha") // Not recommended infix for 5.times(println("ha")) aka dot notation}`

### Most Scala-ish

1. Call by name
2. Type parameterization
3. Implicit method
4. Tail recursion
5. Infix notation
`import scala.annotation.tailrec object Repeat3 extends App {   implicit class UnitWithNtimes(f: => Unit) {    def *[A](n: Int): Unit = { // Symbol * used instead of literal method name      @tailrec      def loop(current: Int): Unit =        if (current > 0) {          f          loop(current - 1)        }      loop(n)    }  }   print("ha") * 5 // * is the method, effective should be A.*(5) }`

## Scheme

Scheme is mostly made up from expressions which return values. However some functions, such as display, return an unspecified value. The actual value returned varies depending on the Scheme implementation itself.

` (import (scheme base)        (scheme write)) (define (repeat proc n)  (do ((i 0 (+ 1 i))       (res '() (cons (proc) res)))    ((= i n) res))) ;; example returning an unspecified value(display (repeat (lambda () (display "hi\n")) 4)) (newline) ;; example returning a number(display (repeat (lambda () (+ 1 2)) 5)) (newline) `
Output:

(Using chibi-scheme: returns #<undef> from display.)

```hi
hi
hi
hi
(#<undef> #<undef> #<undef> #<undef>)
(3 3 3 3 3)
```

## Sidef

`func repeat(f, n) {    { f() } * n;} func example {    say "Example";} repeat(example, 4);`

## Stata

`function repeat(f,n) {	for (i=1; i<=n; i++) (*f)()} function hello() {	printf("Hello\n")} repeat(&hello(),3)`

## Swift

`func repeat(n: Int, f: () -> ()) {  for _ in 0..<n {    f()  }} repeat(4) { println("Example") }`

## Tcl

The usual way of doing a repeat would be:

`proc repeat {command count} {    for {set i 0} {\$i < \$count} {incr i} {        uplevel 1 \$command    }} proc example {} {puts "This is an example"}repeat example 4`

However, the `time` command can be used as long as the return value (the report on the timing information) is ignored.

`time example 4`

It should be noted that the “command” can be an arbitrary script, not just a call to a procedure:

`repeat {puts "hello world"} 3`

## Ursa

`def repeat (function f, int n)	for (set n n) (> n 0) (dec n)		f	end forend repeat def procedure ()	out "Hello! " consoleend procedure # outputs "Hello! " 5 timesrepeat procedure 5`

## VBA

Translation of: Phix
`Private Sub Repeat(rid As String, n As Integer)    For i = 1 To n        Application.Run rid    Next iEnd Sub Private Sub Hello()    Debug.Print "Hello"End Sub Public Sub main()    Repeat "Hello", 5End Sub`

## Visual Basic .NET

Translation of: C#
`Module Module1     Sub Repeat(count As Integer, fn As Action(Of Integer))        If IsNothing(fn) Then            Throw New ArgumentNullException("fn")        End If         For i = 1 To count            fn.Invoke(i)        Next    End Sub     Sub Main()        Repeat(3, Sub(x) Console.WriteLine("Example {0}", x))    End Sub End Module`
Output:
```Example 1
Example 2
Example 3```

## Wren

`var f = Fn.new { |g, n|    for (i in 1..n) g.call(n)} var g = Fn.new { |k|    for (i in 1..k) System.write("%(i) ")    System.print()} f.call(g, 5)`
Output:
```1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
```

## XLISP

`(defun repeat (f n)    (f)    (if (> n 1)        (repeat f (- n 1)) ) ) ;; an example to test it:(repeat (lambda () (print '(hello rosetta code))) 5)`
Output:
```(HELLO ROSETTA CODE)
(HELLO ROSETTA CODE)
(HELLO ROSETTA CODE)
(HELLO ROSETTA CODE)
(HELLO ROSETTA CODE)```

## Yabasic

Translation of: Lua
`sub myFunc ()    print "Sure looks like a function in here..."end sub sub rep (func\$, times)    for count = 1 to times        execute(func\$)    nextend sub rep("myFunc", 4)`

## zkl

`fcn repeat(f,n){ do(n){ f() } }repeat("ho ".print,3);`
Output:
`ho ho ho `