I want to write a function which displays 2 elements in a list in the opposite order. This is my code so far:
(define (reverse-order list)
(cons (rest list) (cons (first list) empty)))
For some reason, this code is not working: For example: If I type in
(reverse-order (cons 1 (cons 2 empty)))
My desired output is
(cons 2 (cons 1 empty))
However, instead, I get
(cons (cons 2 empty) (cons 1 empty))
Any hints on how to go about solving this code will be very helpful.
That's because you're taking the rest
of the list, which is '(2)
, not the second element 2
; and you should not call a parameter list
, that clashes with a built-in procedure of the same name. Try this instead:
(define (reverse-order lst)
(cons (second lst)
(cons (first lst)
empty)))
Or even simpler, and now you see why it was a bad idea to call the parameter list
:
(define (reverse-order lst)
(list (second lst) (first lst)))
Or just use the built-in reverse
procedure :)
(define reverse-order reverse)
Anyway, it works as expected:
(reverse-order '(1 2))
=> '(2 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.