1

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)
Himanshu
  • 2,384
  • 2
  • 24
  • 42

2 Answers2

2

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))
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • Cool. I'll use one of my own for now. I wonder why they left it from the standard. Good to know that it wasn't something too obvious :) – Himanshu Jan 24 '14 at 11:52
  • 2
    @Himanshu Scheme, at least in the earlier versions, is a pretty minimal language. The fact that this was a pretty easy utility to write is a good justification for leaving it out of the language. "It's only three lines, and it's easy to write? We don't need to put it in the spec." :) – Joshua Taylor Jan 24 '14 at 16:07
  • @JoshuaTaylor Yes sounds reasonable. I find Scheme's minimality to be the most attractive features. – Himanshu Jan 25 '14 at 00:22
0

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.

Will Ness
  • 70,110
  • 9
  • 98
  • 181