In Common Lisp, is there a function that returns a symbol from a given string?

隐身守侯 提交于 2019-12-10 15:14:02

问题


I want

>(??? "car")
CAR
>((??? "car") '(1 2))
1 

I can't seem to find a function that does this.


回答1:


Are you looking for this?

(eval (read-from-string "(car '(1 2))"))

Gives: 1


UPDATE:

How about (funcall (intern "CAR") '(1 2)) ? :)




回答2:


There are a few, depending on exactly what you're wanting to do.

First, intern, this will return an existing symbol by that name, if it exists and will otherwise create a new one.

Second, find-symbol, this will return the symbol, if it exists and nil otherwise (it has two return values, the second can be used to distinguish between "returning nil as the symbol" and "returning nil as no symbol found").

Third, there is make-symbol, this will always create a new, uninterned symbol and is almost guaranteed to not be what you want in this specific case.




回答3:


>(??? "car")
CAR
>((??? "car") '(1 2))
1 

use:

CL-USER 17 > (find-symbol "CAR")
CAR
:INHERITED

CL-USER 18 > (funcall (find-symbol "CAR") '(1 2))
1

Note that the names of symbols are internally UPPERCASE in Common Lisp. FUNCALL allows us to call a symbol as a function. One can also use a function object with FUNCALL.

You can also create a form and EVAL that:

CL-USER 19 > (eval `(,(find-symbol "CAR") '(1 2)))
1

or

CL-USER 20 > (eval (list (find-symbol "CAR") ''(1 2)))
1


来源:https://stackoverflow.com/questions/5038155/in-common-lisp-is-there-a-function-that-returns-a-symbol-from-a-given-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!