Page 1 of 1

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

Posted: Mon Nov 11, 2013 11:45 am
by joeish80829
lets say i have a let statement

is this correct

Code: Select all

(let ((x 0))
  (setf x 1))
or will this suffice

Code: Select all

(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

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

Posted: Mon Nov 11, 2013 8:00 pm
by edgar-rft
You do not necessarily need to declare variables, but not declaring variables can easily lead to unwanted behaviour.

Code: Select all

(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.

Code: Select all

(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