The dotimes statement repeats its code a specified number of times. ( dotimes is a standard macro in Common Lisp.) Its format is:

      (dotimes ( var n result ) code )

The variable var is bound inside the dotimes as if it appeared in a let. The value of var is set to 0 and the code is executed; then the value of var is incremented by 1 and the code is repeated, and so on. The total number of executions is n, so the last value of var is n - 1. If n is 0 or negative, the code is not executed.

   (dotimes (i 5) (display i) (display " "))
will write: 0 1 2 3 4 #f

The value of dotimes is result, which is optional; if there is no result, the value is #f.

; Iterative factorial
(define (factorial n)
  (let ((product 1))
    (dotimes (i n product)
      (set! product (* (1+ i) product)) ) ) )

Contents    Page-10    Prev    Next    Page+10    Index