从Lisp中的字符串创建变量名 [英] Create a variable name from a string in Lisp
问题描述
我正在尝试获取一个字符串,并将其转换为变量名。我虽然(make-symbol)或(intern)会这样做,但是显然这不是我想要的,或者我使用的方式不正确。
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.
例如:
> (setf (intern (string "foo")) 5)
> 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?
推荐答案
这里有很多要考虑的事情:
There are a number of things to consider here:
-
SETF
不评估其第一个参数。它需要指定要更新位置的符号或形式。改用SET
。
SETF
does not evaluate its first argument. It expects a symbol or a form that specifies a location to update. UseSET
instead.
根据Common Lisp实现的年份和设置,符号名称可能会不同。默认为大写。因此,第二个对 foo
的引用实际上可能指向名称为 FOO
的符号。在这种情况下,您将需要使用(实习生 FOO)
。
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")
.
对 STRING
是无害的,但如果值已经是字符串,则是不必要的。
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
这篇关于从Lisp中的字符串创建变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!