我正在尝试编写一个函数,使得对于任何整数 x 的 P(x) 都有一个包含三个元素的列表,即平方、立方和 n 的四次方,但我仍然不知道如何组合然后制作一个函数,例如我有平方、立方体和 4 次幂函数 下面是我的函数
(defun p(x) (* x x))
(defun p(x) (* x x x))
(defun p(x) (expt x x) //thought i am not sure about this one
有没有办法让我的结果(即 function p(x)
)列表看起来像 (4 27 256)
如果我有 ( 2 3 4)
执行程序后?正在考虑 mapcar 函数
,但我不确定如何去做。有什么建议么?
最佳答案
是的,mapcar
可能是一条路。
;; a simple solution.
(defun expt-list (n powers)
(mapcar #'(lambda (x) (expt n x)) powers))
;; a bit more complex, so you don't compute powers of the same
;; base multiple times.
(defun expt-list-memoize (n powers)
(let ((hash (make-hash-table)))
(mapcar #'(lambda (x)
(let ((y (gethash x hash)))
(if y y (setf (gethash x hash) (expt n x)))))
powers)))
关于list - 常用 lisp 函数中的表达式和算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12787609/