PDA

View Full Version : variable formulation


andrea
01-24-2005, 07:01 AM
I have these variable ones
(setf tmp1 "/image")
(setf tmp2 "/pic")
(setf num-p 1)

(setf tmp-tot (format nil "tmp~A" num-p))

Why the result of the variable tmp-tot is not the value of the variable one "tmp1" but it is string it "tmp1"?
I wanted like result of tmp-tot the value of the variable one tmp1 ....

it is possible?

P.S:
The solution would be easy
(setf tmp-tot tmp1)
But cosi I cannot must depend also on the variable one num-1
Why if the variable one (setf num-p 2) the final value of tmp-tot it must be equal to the value of the variable one tmp2 (/pic).

John van Doorn
01-24-2005, 11:18 AM
Hi Andrea,

The following line will do the trick: :D

(setf tmp-tot (eval(read-from-string(format nil "tmp~A" num-p))))


With format nil you are just building a string.with read-from-string you tell the lisp reader to read that string just like load would do as if it was coming from a file.
Last eval will read the value of the symbol.

Hope this helps,
John

clausb
01-24-2005, 11:29 AM
Don't get me wrong, I'm not trying to pick on you - but I'd really recommend to buy a book on LISP and read it, or at least work through a tutorial. If you don't understand why the format statement behaves like it does, you can probably save yourself a *LOT* of time by learning the basics first. You'll find links to free online and commercial LISP books at http://www.clausbrod.de/Osdm/OsdmFaqLinks .

(format nil "tmp~A" num-p) takes the value (!) of num-p (which is 1) and converts it according to the conversion specifier ~A, i.e. it converts it into its string representation. Which is why format's result is "tmp1". See also the documentation on format at http://www.lisp.org/HyperSpec/Body/fun_format.html#format .

If you need an indirection, you could create an array of LISP strings (via make-array, see http://www.lisp.org/HyperSpec/Body/fun_make-array.html for details) and use num-p as an index into it.

If you know that the list of values is small, you could simply use a LISP list:

(setf vals '("/image" "/pic"))
(setf num-p 1) ;; first entry = 0, second entry = 1
(setf tmp-tot (nth num-p vals))


In LISP, there are also many other ways to accomplish the same or something very similar. Which of those methods is the best really depends on your particular problem, performance requirements, data set sizes etc.

Claus

andrea
01-24-2005, 10:54 PM
Thanks John van Doorn are perfect.....

:) :) :) :) :)

John van Doorn
01-25-2005, 02:42 AM
Andrea,

Glad I could help, but I have to agree with Claus, that the provided solution is not a good practice. :rolleyes:

So if I where you, I would seriously consider Claus advice :)

John