common-lisp - 如何在 Common Lisp 中创建函数指针数组?
问题描述
我有一个程序需要具有一系列可互换的功能。
在 c++ 中,我可以做一个简单的typedef
陈述。然后我可以调用该列表中的一个函数function[variable]
。如何在 Common Lisp 中做到这一点?
解决方案
在 Common Lisp中,一切都是对象值,包括函数。(lambda (x) (* x x))
返回一个函数值。该值是函数所在的地址或类似的地址,因此只需将其放在列表、向量 og 哈希中,您就可以获取该值并调用它。这是一个使用列表的示例:
;; this creates a normal function in the function namespace in the current package
(defun sub (a b)
(- a b))
;; this creates a function object bound to a variable
(defparameter *hyp* (lambda (a b) (sqrt (+ (* a a) (* b b)))))
;; this creates a lookup list of functions to call
(defparameter *funs*
(list (function +) ; a standard function object can be fetched by name with function
#'sub ; same as function, just shorter syntax
*hyp*)) ; variable *hyp* evaluates to a function
;; call one of the functions (*hyp*)
(funcall (third *funs*)
3
4)
; ==> 5
;; map over all the functions in the list with `3` and `4` as arguments
(mapcar (lambda (fun)
(funcall fun 3 4))
*funs*)
; ==> (7 -1 5)
推荐阅读
- javascript - Javascript Loop 不等待 Firebase 完成上传多个文件
- python-3.x - Python:在列表中查找一个数字(较小但最大)
- php - 如何显示仅在 3 小时前发布的结果
- angular - Angular 7 Promise 效果不佳?一次成功块,错误块
- react-native - 反应本机-Android:
- kotlin - View.setMargins 的 Kotlin 扩展函数
- python - 如何在变量名中使用“-”减号进行查询和打印
- deep-learning - 关于 RetinaNet 的困惑
- visual-studio-code - Flutter 包进入 VS Code 失败
- regex - 匹配某些字符和单个通配符的正则表达式