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

Discussion of Common Lisp

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

Postby joeish80829 » Mon Nov 11, 2013 11:45 am

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
Last edited by joeish80829 on Tue Nov 12, 2013 4:48 am, edited 1 time in total.
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

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

Postby edgar-rft » Mon Nov 11, 2013 8:00 pm

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
Posts: 224
Joined: Fri Aug 06, 2010 6:34 am
Location: Germany

Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 6 guests