【问题标题】:Expressions and arithemetics in common lisp functions常用 lisp 函数中的表达式和算术运算
【发布时间】:2012-10-08 18:45:36
【问题描述】:

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

如果我在执行程序后有一个( 2 3 4) 列表,有没有办法让我的结果(即function p(x))列表看起来像(4 27 256)?正在考虑mapcar function,尽管我不确定如何去做。有什么建议么?

【问题讨论】:

  • 如果要创建列表,函数LIST怎么样?
  • 我想过但我只是一个新手不知道如何操作函数

标签: list functional-programming lisp common-lisp


【解决方案1】:

是的,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)))

【讨论】:

  • 我如何输入数字或参数它给出一些错误我不知道为什么
  • 我在最后得到了 expt-list 但是当我进入 (expt-list 2 3 5) 时它不起作用,我错过了什么吗?
【解决方案2】:

Common Lisp 中有一个奇怪的地方,我们必须认识到:如果你想通过一个符号来引用一个函数,你必须用 (function p) 或缩写 #'p

来引用它。 >

给定

(defun p(x) (* x x))

你可以计算一个正方形列表

CL-USER> (mapcar #'p (list 1 2 3 4))

(1 4 9 16)

【讨论】:

    【解决方案3】:

    这里的要求有点模糊,但如果意图是,给定一个诸如(expt-list 2 3 4) 之类的调用以返回每个提升到其自身权力的数字的列表,例如:

    (expt-list 2 3 4)
    => (4 27 256)
    

    会是这样的:

    (defun expt-list (&rest list-of-n)
      "return a list of each 'n' in LIST-OF-N raised to its own power"
      (loop for n in list-of-n collect (expt n n)))
    

    做这个伎俩?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多