39 lines
1.2 KiB
Common Lisp
39 lines
1.2 KiB
Common Lisp
;;; LOOPS 5: DO AND DO*
|
|
;;;
|
|
;;; DO is LOOP's ancestor, spelled out:
|
|
;;;
|
|
;;; (do ((i 1 (1+ i)) (total 0 (+ total i)))
|
|
;;; ((> i n) total))
|
|
;;;
|
|
;;; Each variable gets an initializer and a STEP. The step
|
|
;;; expressions all see the OLD values - like LET. DO* steps one at
|
|
;;; a time - like LET* - so a later step can use an earlier
|
|
;;; variable's NEW value. That difference is exactly what the
|
|
;;; factorial below needs.
|
|
|
|
;; TODO: The sum 1 + 2 + ... + N, the DO way.
|
|
(defun triangle-do (n)
|
|
(do ((i 1 (1+ i))
|
|
(total 0 total))
|
|
((> i n) total)))
|
|
|
|
;; TODO: N factorial: 1 * 2 * ... * N, with B seeing A's new value
|
|
;; - DO*, not DO.
|
|
(defun factorial-of (n)
|
|
(do ((a 1 (1+ a))
|
|
(b 1 (* b a)))
|
|
((>= a n) b)))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal 6 (triangle-do 3))
|
|
(check-equal 55 (triangle-do 10))
|
|
(check-equal 0 (triangle-do 0))
|
|
(check-equal 1 (factorial-of 0))
|
|
(check-equal 1 (factorial-of 1))
|
|
(check-equal 6 (factorial-of 3))
|
|
(check-equal 24 (factorial-of 4))
|