list - 常用 lisp 函数中的表达式和算术

标签 list functional-programming lisp common-lisp

我正在尝试编写一个函数,使得对于任何整数 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/

相关文章:

oop - 函数式编程中的重构是否比 OOP 中的重构更困难?

java - Scala 中的类、对象、特征、密封特征

java - Java 中 C++ 的 std::bind 是否等效?

lisp - 为什么将 "(null x)"替换为 "(null (cdr x))"会使此代码有效?

lisp - 如何在 Common Lisp 中返回变量的值和名称

java - 警告 ArrayList 是原始类型。应参数化对泛型类型 ArrayList<E> 的引用

c# - 在 List<Tuple> 中的 Item2 中搜索

Python 内置列表 : remove one item

python - 分配如何与列表切片一起使用?

clojure - Clojure(或任何其他 Lisp)中 + 函数的类型是什么?