14

I'm trying to take a string, and convert it into a variable name. I though (make-symbol) or (intern) would do this, but apparently it's not quite what I want, or I'm using it incorrectly.

For example:

> (setf (intern (string "foo")) 5)
> foo
  5

Here I would be trying to create a variable named 'foo' with a value of 5. Except, the above code gives me an error. What is the command I'm looking for?

2 Answers 2

15

There are a number of things to consider here:

  1. SETF does not evaluate its first argument. It expects a symbol or a form that specifies a location to update. Use SET instead.

  2. Depending upon the vintage and settings of your Common Lisp implementation, symbol names may default to upper case. Thus, the second reference to foo may actually refer to a symbol whose name is "FOO". In this case, you would need to use (intern "FOO").

  3. The call to STRING is harmless but unnecessary if the value is already a string.

Putting it all together, try this:

> (set (intern "FOO") 5)
> foo
  5
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, that worked! Well, sort of. I'm actually not trying to assign values using (set) but using another function called (add-dm) which I didn't create. Apparently, (add-dm) has the same limitation as (setf), where the first expression is not evaluated, so I'll have to figure out another way. But that did shed some light on things, so thanks! (Also, I do realize that (string) is unnecessary, though my ultimate goal is to create a symbol from concatenated strings, so I kept it in just in case it made a difference).
@Jeff If ADD-DM is a macro, it might expand to an exported function that can be used in the same manner as SET. Try inspecting the result of (macroexpand-1 '(add-dm ...)) to see if you are in luck.
9

Use:

CL-USER 7 > (setf (SYMBOL-VALUE (INTERN "FOO")) 5) 
5

CL-USER 8 > foo
5

This also works with a variable:

CL-USER 11 > (let ((sym-name "FOO"))
               (setf (SYMBOL-VALUE (INTERN sym-name)) 3))
3

CL-USER 12 > foo
3

Remember also that by default symbols are created internally as uppercase. If you want to access a symbol via a string, you have to use an uppercase string then.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.