3

I'm doing some homework in Lisp, using clisp to test, and I'm loading this code and running in in clisp

(defun myreverse (thelist)

(reverse thelist)
(print thelist)

(if (equal thelist nil)
    nil
    (if (consp (first thelist))
            (cons (myreverse (reverse (first thelist))) 
                (myreverse (reverse (rest thelist))))
            (cons (first thelist) (myreverse (rest thelist))))))

I'm kind of new to Lisp, but this code isn't reversing thelist at all, my output is:

[18]> (myreverse '(a (b c) d))

(A (B C) D)
((B C) D)
(C B)
(B)
NIL
(D)
NIL
(A (C B) D)

The first line of my code says (reverse thelist), why isn't it reversing for the first print statement? Am I missing something?

1
  • 1
    (null thelist) is more idiomatic than (equal thelist nil) in Common Lisp. Commented Jan 18, 2012 at 17:42

1 Answer 1

4

I believe (reverse) is without side-effects, thus it doesn't reverse the original list, but returns a new, reversed one. This is not so natural in Common Lisp, but expected in Scheme. Nevertheless, here is the doc http://www.lispworks.com/documentation/HyperSpec/Body/f_revers.htm#reverse

What I think you want is (nreverse).

Sign up to request clarification or add additional context in comments.

6 Comments

Ah ok, so it reverses (B C) because when it returns list it actually goes somewhere else in the code (i.e. - reverse-all)?
Yeah it just prints thelist, which happens to be the result of (reverse (first thelist)) in that case
Awesome, thanks so much I was really confused there for a second.
So anyway, what you want is, in the beginning instead of (reverse thelist) something like (nreverse thelist)
I think it's worth noting that even for functions like (nreverse thelist) that modify the list in place you have to consume the return value (e.g. (let ((x (list 1 2 3))) (setf x (nreverse x)))).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.