簡體   English   中英

返回列表的多維數據集函數的CLISP遞歸功能

[英]CLISP recursive powers of cubes function that returns a list

我在編寫返回前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。 謝謝您的幫助!

是的,您的函數有一個小問題::-)

  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))))

您還可以使用循環工具,並且應該檢查dec的初始值是否為正,否則可能會導致無限循環/遞歸:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM