"I have a mind like a steel... uh... thingy." Patrick Logan's weblog.

Search This Blog

Sunday, January 25, 2004

Idiomatic Lisp and Idiomatic Scheme

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)
	 (loop (- n 1) (* n acc)))))

;; "Old School" Common Lisp
(defun fact(n &optional (acc 1))
  (if (<= n 1)
    (fact (- n 1) (* n acc)))

No comments:

Blog Archive

About Me

Portland, Oregon, United States
I'm usually writing from my favorite location on the planet, the pacific northwest of the u.s. I write for myself only and unless otherwise specified my posts here should not be taken as representing an official position of my employer. Contact me at my gee mail account, username patrickdlogan.