This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

do i need to decare a variable before i use setf in a let

2 posts · 2776 views

lets say i have a let statement

is this correct
(let ((x 0))
  (setf x 1))
or will this suffice
(let ((y 0) ; y = 0 is for place holder)
  (setf x 1))
i dont want to cause any bugs or slowness so if someone can tell me which of the above is faster or less buggy or if both are perfect i would be much appreciative...i know both work but google had no leads

Last edited by joeish80829 on , edited 1 time in total.

Re: do i need to decare a variable before i use setf in a le

You do not necessarily need to declare variables, but not declaring variables can easily lead to unwanted behaviour.
(let ((x 0))
  (setf x 1))
Here (setf x 1) changes the lexically scoped variable x, bound by (let ((x 0)) ...), from 0 to 1. There are no other "invisible" side-effects you need to care about.
(let ((y 0))
  (setf x 1))
Here the behaviour of x depends on the surrounding code. If there was no other appearance of an x variable in the code before, then (setf x 1) will create a dynamically scoped variable as if x was defined by DEFVAR. This is a different behaviour of x than in the first example above.

The difference between lexical dand dynamic scope is explained in Practical Common Lisp, Chapter 6 Variables

Everything that has to do with speed is entirely implementation dependent. Exactly the same Lisp code can run at different speeds with different Lisp implementations.
Common Lisp symbols that can influence the run-time speed:
Common Lisp symbols used in declarations:
Note that the support for declarations is optional, a Common Lisp compiler is free to ignore all of the symbols above. The only way to find out the exact effect of the symbols is reading the documentation of the specific Common Lisp implementation.

Common Lisp provides the TIME macro to test how fast a specific piece of Lisp code runs and the DISASSEMBLE function to look at the low-level code that the compiler produces.

- edgar