I guess I agree with Brian Marick's code reading style more than Richard Gabriel's. Rather than using an optional private parameter in a public function, though, I prefer to use the "named" let
, with an accumulator there, for tail recursive functions.
Is it idiomatic? It's fairly common in Scheme. I am not sure why it has not been adopted more widely into Common Lisp.
;; Richard Gabriel's Idiomatic Common Lisp
(defun fact (n)
(labels ((f (n acc)
(if (<= n 1) acc (f (- n 1) (* n acc)))))
(f n 1)))
;; My (Idiomatic?) Scheme
(define (fact n)
(let loop ((n n) (acc 1))
(if (<= n 1)
acc
(loop (- n 1) (* n acc)))))
;; "Old School" Common Lisp
(defun fact(n &optional (acc 1))
(if (<= n 1)
acc
(fact (- n 1) (* n acc)))
No comments:
Post a Comment