Repeat: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|REXX}}: added an example for an external procedure to be invoked a number of times.)
(added ocaml)
Line 108: Line 108:
hi
hi
hi
hi
</lang>

=={{header|OCaml}}==

<lang ocaml>let repeat ~f ~n =
for i = 1 to n do
f ()
done

let func () =
print_endline "Example"

let () =
repeat ~n:4 ~f:func
</lang>
</lang>



Revision as of 20:35, 8 June 2014

Repeat is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

The task is to 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.

C

<lang c>#include <stdio.h>

void repeat(void (*f)(void), int n) {

for(int i=n; 0<i; i--)
(*f)();

}

void example() {

printf("Example\n");

}

void main(char *argv[], int argc) {

repeat(example, 4);

}</lang>

Common Lisp

<lang lisp>(defun repeat (f n)

 (dotimes (i n) (funcall f)))

(repeat (lambda () (format T "Example~%")) 5)</lang>

D

<lang 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);

}</lang>

Output:
Example
Example
Example

Haskell

<lang Haskell>rep :: Monad m => m () -> Integer -> m () rep _ 0 = return () rep f n = f >> rep f (n-1)

sampleFunction :: IO () sampleFunction = putStrLn "a"

main = rep sampleFunction 5</lang>

J

<lang J>

  NB. ^: (J's power conjunction) repeatedly evaluates a verb.
  NB. Appending to a vector the sum of the most recent
  NB. 2 items can generate the Fibonacci sequence.
  (, [: +/ _2&{.)  (^:4)  0 1

0 1 1 2 3 5


  NB. Repeat an infinite number of times
  NB. computes the stable point at convergence
  cosine =: 2&o.
  cosine (^:_ ) 2    NB. 2 is the initial value

0.739085

  cosine 0.739085  NB. demonstrate the stable point x==Cos(x)

0.739085


  cosine^:(<_) 2  NB. show the convergence

2 _0.416147 0.914653 0.610065 0.819611 0.682506 0.775995 0.713725 0.755929 0.727635 0.74675 0.733901 0.742568 0.736735 0.740666 0.738019 0.739803 0.738602 0.739411 0.738866 0.739233 0.738986 0.739152 0.73904 0.739116 0.739065 0.739099 0.739076 0.739091 0.7...


  # cosine^:(<_) 2  NB. iteration tallyft

78

  f =: 3 :'smoutput hi'
  f

hi

  NB. pass verbs via a gerund
  repeat =: dyad def 'for_i. i.y do. (x`:0)0 end. EMPTY'
  (f`)repeat 4

hi hi hi hi


  NB. pass a verb directly to an adverb
  Repeat =: adverb def 'for_i. i.y do. u 0 end. EMPTY'
  f Repeat 4

hi hi hi hi </lang>

OCaml

<lang ocaml>let repeat ~f ~n =

 for i = 1 to n do
   f ()
 done

let func () =

 print_endline "Example"

let () =

 repeat ~n:4 ~f:func

</lang>

Perl 6

Perl 6 has a built in infix repeat operator (xx) that does this. It returns a list of whatever is on the left side (string, function, subroutine, whatever) times whatever integer is on the right. Nominally it is for building lists but can be used for side effects too. It could be argued that this is an operator, not a procedure, but in Perl 6, operators are just subroutines with funny calling conventions.

Print a list consisting of repeated strings. <lang Perl6>say <Again> xx 4;</lang>

Output:
   Again Again Again Again

Use it for side effects. Execute the code inside the parenthesis repeatedly. <lang Perl6>(say <Again>) xx 3;</lang>

Output:
   Again
   Again
   Again

Print a list built by executing the built in rand function repeatedly. <lang Perl6>say rand xx 5;</lang>

Output:
   0.313024826146821 0.231583221230768 0.439756228609952 0.870180182595826 0.650911888509852

Create a small subroutine, call it repeatedly then print the result. <lang Perl6>sub boguscode () { sleep 1; time; } my @times = boguscode() xx 4; say @times;</lang>

Output:
   1400450920 1400450921 1400450922 1400450923

Python

<lang Python>#!/usr/bin/python def repeat(f,n):

 for i in range(n):
   f();

def procedure():

 print("Example");

repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.</lang>

Racket

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

<lang Racket>#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)</lang>

Output:
... and over and over and over and over and over... & over & over & over & over & over

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. <lang rexx>/*REXX program executes a named procedure a specified number of times.*/ parse arg procName times . /*obtain optional parms from C.L.*/ call repeats procName,times /*invoke the REPEATS procedure.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────REPEATS subroutine──────────────────*/ repeats: procedure; parse arg Pname,x /*get procedureName & # of times.*/

             do x;  interpret 'CALL' pName;  end    /*repeat  X  times.*/

return /*return to invoker*/ /*──────────────────────────────────YABBA subroutine────────────────────*/ yabba: procedure; say 'Yabba, yabba do!'; return</lang> 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 5
[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

Ruby

<lang ruby>4.times{ puts "Example" } # idiomatic way

def repeat(proc,num)

 num.times{ proc.call }

end

repeat(->{ puts "Example" }, 4)</lang>

Scala

<lang scala>def repeat(n:Int)(f: => Unit)= for(_ <- 0 until n)(f)

repeat(3){

  println("Example")

}</lang>

Tcl

The usual way of doing a repeat would be: <lang tcl>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</lang> However, the time command can be used as long as the return value (the report on the timing information) is ignored. <lang tcl>time example 4</lang> It should be noted that the “command” can be an arbitrary script, not just a call to a procedure: <lang tcl>repeat {puts "hello world"} 3</lang>