首页 > 解决方案 > 如何在 Common Lisp 中创建函数指针数组?

问题描述

我有一个程序需要具有一系列可互换的功能。

在 c++ 中,我可以做一个简单的typedef陈述。然后我可以调用该列表中的一个函数function[variable]。如何在 Common Lisp 中做到这一点?

标签: common-lispansi-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)

推荐阅读