Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a variable name from a string in Lisp

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?

like image 643
Jeff Avatar asked Mar 15 '11 02:03

Jeff


People also ask

What is let * In Lisp?

The let expression is a special form in Lisp that you will need to use in most function definitions. let is used to attach or bind a symbol to a value in such a way that the Lisp interpreter will not confuse the variable with a variable of the same name that is not part of the function.

How do you declare a global variable in Lisp?

Defining a global variable: New global variables can be defined using DEFVAR and DEFPARAMETER construct. The difference between both of them is that DEFPARAMETER always assigns initial value and DEFVAR form can be used to create a global variable without giving it a value.

What is SETQ in Lisp?

(setq var1 form1 var2 form2 ...) is the simple variable assignment statement of Lisp. First form1 is evaluated and the result is stored in the variable var1, then form2 is evaluated and the result stored in var2, and so forth. setq may be used for assignment of both lexical and dynamic variables.


2 Answers

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
like image 65
WReach Avatar answered Oct 13 '22 04:10

WReach


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.

like image 22
Rainer Joswig Avatar answered Oct 13 '22 03:10

Rainer Joswig