【问题标题】:CLISP recursive powers of cubes function that returns a list返回列表的多维数据集函数的 CLISP 递归幂
【发布时间】:2015-01-27 08:25:58
【问题描述】:

我在编写一个返回前 15 个立方体列表的函数时寻求帮助。这是我目前所拥有的,我遇到了堆栈溢出:

(defun cubes (dec lst) ;takes a number and a list as params
   (if (= dec 0) lst ;if dec is 0 return the list
       (cons (threes (- dec 1) lst))) ;;else decrement and call it again
)

我用以下代码调用它:

(cubes 15 nil) ;should print first 15 cubes

我今天刚开始学习 LISP。感谢您的帮助!

【问题讨论】:

  • 你不想在某个地方计算立方体吗?

标签: function recursion lisp common-lisp exponent


【解决方案1】:

是的,你的函数有一点问题::-)

  1. 您将递归到 threes 而不是 cubes
  2. 您正在尝试使用一个参数调用 cons(它需要两个参数)。
  3. 您不会在递归中更改lst 的值,因此,由于基本情况返回lst,您将始终获得您传入的初始lst 值。

这是一个固定版本:

(defun cubes (dec lst)
  (if (zerop dec)
      lst
      (cubes (1- dec) (cons (* dec dec dec) lst))))

【讨论】:

  • 你不想在某个地方计算立方体吗?
  • @Svante 哎呀。过于专注于让代码正常工作而忽略了查看问题域。
  • @DomnWerner (* dec dec dec) 与中缀中的 dec * dec * dec 相同。它基本上计算为dec 的立方体。
【解决方案2】:

你也可以使用循环功能,你应该检查 dec 的初始值是否为正,否则你可能会陷入无限循环/递归:

(defun cubes (dec lst)
       (append
          (when (plusp dec)
                (loop for i from 1 to dec collect (expt i 3)))
          lst))

【讨论】:

  • 你不需要lstappendwhen
  • 我的意思是:(defun cubes (n) (when (plusp n) (loop :for i :from 1 :to n :collect (expt i 3))))
  • 没错,但是作者的函数接受了一个整数和一个列表,所以建议的变体也应该如此。
  • (defun cubes (n list) (declare (ignore list)) (when (plusp n) (loop :for i :from 1 :to n :collect (expt i 3))))
  • 作者的变体将立方体限制为作为第二个参数给出的列表,而您的则忽略它。当我编写我的变体时,我考虑了原始变体的实际作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
相关资源
最近更新 更多