Why does this "let" work?

Discussion of Common Lisp
Post Reply
amachina
Posts: 2
Joined: Mon Jul 25, 2011 3:19 pm

Why does this "let" work?

Post by amachina » Mon Jul 25, 2011 3:36 pm

Code: Select all

(defun add ()
...(let ((sum 0) next)
......(loop
.........(setq next (read))
.........(cond ((numberp next) (incf sum next))
............(eq '= next) (print sum) (return))
............(t (format t "~&~a ignored~%" next))))
.......(values)))
I thought the structure of a let is:

(let (bindings) forms)
where (bindings) is any number of two-element lists:

Code: Select all

(let ((a 0)
       (b 1))
  (form))
Above, (let ((sum 0) next) ...
does not seem to follow that rule

(BTW: How do I write lisp code here so that it is nicelfy formatted --- sorry - haven't had a chance to read the FAQ yet -- I will)

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: Why does this "let" work?

Post by gugamilare » Mon Jul 25, 2011 6:14 pm

When no value is given to a variable being declared with let, it is assigned to NIL

Therefore, this:

Code: Select all

(let ((sum 0) next)
  ...)
this:

Code: Select all

(let ((sum 0) (next))
  ...)
and this:

Code: Select all

(let ((sum 0) (next nil))
  ...)
they all mean the same thing.

Note: to insert Lisp code in this forum, put it like this:

Code: Select all

[code]<Lisp code here>
[/code]

amachina
Posts: 2
Joined: Mon Jul 25, 2011 3:19 pm

Re: Why does this "let" work?

Post by amachina » Tue Jul 26, 2011 9:05 am

Thanks. That allows me to move forward. As you said, all of these are equivalent:

Code: Select all

(let ((a 0) b)
 
(let ((a 0)
      (b nil))

(let ((a 0)
      (b))
I like the middle one because it "follows the rules".

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: Why does this "let" work?

Post by gugamilare » Tue Jul 26, 2011 10:35 am

You are welcome :)

Paul
Posts: 106
Joined: Tue Jun 02, 2009 6:00 am

Re: Why does this "let" work?

Post by Paul » Tue Jul 26, 2011 2:54 pm

amachina wrote:Thanks. That allows me to move forward. As you said, all of these are equivalent:

Code: Select all

(let ((a 0) b)
 
(let ((a 0)
      (b nil))

(let ((a 0)
      (b))
I like the middle one because it "follows the rules".
They all "follow the rules"...

Post Reply