Search code examples
schemeguile

scheme function to call a procedure n times


Does scheme have a function to call a function n times. I don't want map/for-each as the function doesn't have any arguments. Something along the lines of this :-

(define (call-n-times proc n)
        (if (= 0 n)
            '()
            (cons (proc) (call-n-times proc (- n 1)))))

(call-n-times read 10)

Solution

  • SRFI 1 has a list-tabulate function that can build a list from calling a given function, with arguments 0 through (- n 1). However, it does not guarantee the order of execution (in fact, many implementations start from (- n 1) and go down), so it's not ideal for calling read with.

    In Racket, you can do this:

    (for/list ((i 10))
      (read))
    

    to call read 10 times and collect the result of each; and it would be done left-to-right. But since you tagged your question for Guile, we need to do something different.

    Luckily, Guile has SRFI 42, which enables you to do:

    (list-ec (: i 10)
      (read))