Why aren't these equivalent?

Discussion of Common Lisp
Post Reply
jordan
Posts: 4
Joined: Wed Oct 22, 2008 1:47 pm

Why aren't these equivalent?

Post by jordan » Wed Oct 22, 2008 1:56 pm

Hello, noob question here. I'm coding up some DO loop examples to help me understand it. I eventually got my example working, but I'm curious why a previous version did NOT work.

The working one:

Code: Select all

(defun add-inputs ()
  "Add a series of numbers from input"
  (do ((input (get-integer-from-input) (get-integer-from-input))
       (sum 0 (+ sum input)))
      ((= input 0) sum)))
The non-working one, that I thought would be equivalent:

Code: Select all

(defun add-inputs-broken ()
  "Add a series of numbers from input"
  (do ((input (get-integer-from-input))
       (sum 0 (+ sum input)))
      ((= input 0) sum)
    (setf input (get-integer-from-input))))

Jasper
Posts: 209
Joined: Fri Oct 10, 2008 8:22 am
Location: Eindhoven, The Netherlands
Contact:

Re: Why aren't these equivalent?

Post by Jasper » Wed Oct 22, 2008 6:26 pm

Code: Select all

(do ((i 0 (+ i 1)) (list nil (cons list i)) ((= i 10) list))
(do ((i 0) (list nil (cons list i)) ((= i 10) list) (setf i (+ i 1))
Compare those. the 'do body is done before the 'increment' operations.

jordan
Posts: 4
Joined: Wed Oct 22, 2008 1:47 pm

Re: Why aren't these equivalent?

Post by jordan » Wed Oct 22, 2008 10:00 pm

Ah, I see your point, I was clobbering my initial value before making use of it with the other variable's increment statement.

Thanks!

Post Reply