Question

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)
Was it helpful?

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

OTHER TIPS

Implementing tail-recursion modulo cons optimization by hand, to build the resulting list with O(1) extra space:

(define (iterate0-n proc n)   ; iterate a 0-arguments procedure n times
  (let ((res (list 1)))       ; return a list of results in order
    (let loop ((i n) (p res))
      (if (< i 1)
        (cdr res)
        (begin
          (set-cdr! p (list (proc)))
          (loop (- i 1) (cdr p)))))))

This technique first (?) described in Friedman and Wise's TR19.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top