Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between the "for" and "as" keywords in the loop macro?

Tags:

common-lisp

In Common Lisp, in the loop macro, the and and as keywords appear to function identically:

(loop for i from 1 to 3 do (print i))
(loop as i from 1 to 3 do (print i))

Is there some subtle difference I'm missing? If not, why bother with two different yet identical keywords?

like image 328
Gustav Bertram Avatar asked Mar 11 '23 00:03

Gustav Bertram


1 Answers

6.1.2.1 Iteration Control:

The for and as keywords are synonyms; they can be used interchangeably. ... By convention, for introduces new iterations and as introduces iterations that depend on a previous iteration specification.

E.g.:

(loop for x from 1 to 10
  as x2 = (* x x)
  as x4 = (* x2 x2)
  for y from 10 downto 1
  as y2 = (* y y)
  as y4 = (* y2 y2)
  sum (* x4 y4))

Why?!

Tradition! :-)

And, also...

"... a computer language is not just a way of getting a computer to perform operations, but rather ... it is a novel formal medium for expressing ideas about methodology" Abelson/Sussman "Structure and Interpretation of Computer Programs".

IOW, we write code for people (including you 6 months from now) to read, not just for computers to execute.

Everything that makes your code more readable is "fair game".

like image 169
sds Avatar answered Mar 12 '23 14:03

sds