Вопрос по – CLISP - Перевернуть простой список

2

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

(defun LISTREVERSE (LISTR)
    (cond
        ((< (length LISTR) 2) LISTR) ; listr is 1 atom or smaller
        (t (cons (LISTREVERSE (cdr LISTR)) (car LISTR))) ; move first to the end
    )
)

Error: User Rate Limit Exceeded

[88]> (LISTREVERSE '(0 1 2 3)) 
((((3) . 2) . 1) . 0)

Error: User Rate Limit ExceededappendError: User Rate Limit Exceededcons:

(t (append (LISTREVERSE (cdr LISTR)) (car LISTR)))

Error: User Rate Limit Exceeded

*** - APPEND: A proper list must not end with 2

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded Rainer Joswig
Error: User Rate Limit ExceededappendError: User Rate Limit Exceeded Marcin
Error: User Rate Limit Exceeded Rainer Joswig

Ваш Ответ

4   ответа
0

(defun LISTREVERSE (LISTR)
    (cons
        ((< (length LISTR) 2) LISTR) ; listr is 1 atom or smaller
        (t (append (LISTREVERSE (cdr LISTR)) (list (car  LISTR))))))
6

The base case of the recursion is when the list is empty (null), and not when there are less than two elements in the list Consider defining a helper function with an extra parameter, an "accumulator" initialized in the empty list. For each element in the original list, cons it at the head of the accumulator. When the input list is empty, return the accumulator

Error: User Rate Limit ExceededpreciselyError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded((((NIL 3) 2) 1) 0)Error: User Rate Limit Exceeded user1342836
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded user1342836
Error: User Rate Limit Exceeded user1342836
0

(defun listreverse (list)
  (let (result)
    (dolist (item list result)
      (push item result))))
Don't use recursion in Common Lisp when there is a simple iterative way to reach the same goal. Common Lisp does not make any guarantees about tail recursion, and your tail recursive function invocation may not be optimized to a jump at the discretion of the compiler. push prepends the item to the result dolist has an optional third argument which is the value returned. It is evaluated when the loop is exited.
3

Using both append and length makes the posted solution just about the least efficient way of reversing a list. Check out the documentation on cons and null for some better ideas on how to implement this. Please, please indent properly. Tail recursion really is both more efficient and reasonably simple in this case. Try it if you haven't already. labels is the form you want to use to define local recursive functions. It may be worth your while to flip through The Little Schemer. It'll give you a better feel for recursion in general.
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceedednotError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

Похожие вопросы