gpt4 book ai didi

common-lisp - 将字符串转换为函数

转载 作者:行者123 更新时间:2023-12-02 01:25:39 25 4
gpt4 key购买 nike

我有字符串“+”,我想将其转换为#'+。基本上我想将字符串映射到相应的函数即“myfunname”到#'myfunname。

最佳答案

这几乎肯定是一个 XY 问题:为什么要从字符串开始?

如果您确实需要将字符串转换为函数,那么类似下面的代码就可以做到这一点,并且比使用read安全得多:

(defun string->function (name &key (readtable-case (readtable-case *readtable*))
(package *package*))
(let ((effective-name (map 'string
(ecase readtable-case
((:upcase)
#'char-upcase)
((:downcase)
#'char-downcase)
((:preserve)
#'identity)
((:invert)
(lambda (c)
(cond
((upper-case-p c)
(char-downcase c))
((lower-case-p c)
(char-upcase c))
(t c)))))
name)))
(multiple-value-bind (s status) (find-symbol effective-name package)
(unless status
(error "no symbol for ~S (from ~S)" effective-name name))
(unless (fboundp s)
(error "no function for ~S (from ~S, originally ~S)" s effective-name name))
(symbol-function s))))

现在

> (string->function "+")
#<Function + 80E004F189>

> (eql (string->function "+") #'+)
t

> (string->function "string->function")
#<Function string->function 80200011E9>

> (string->function "unknown")

Error: no symbol for "UNKNOWN" (from "unknown")

> (string->function "*print-case*")

Error: no function for *print-case* (from "*PRINT-CASE*", originally "*print-case*")

关于common-lisp - 将字符串转换为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74768048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com