Repeat
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>
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>
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!
I'm not smart enough to do the Captcha, so here's some of the URL: docs.racket-lang.org/guide/for.html?q=iterators
<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