Reputation: 93
Trying to rotate a list left in scheme/racket. For example: (rotate-left '(abc)) outputs (bca)
Here's ze code!
(define (rotate-left LIST)
(if(null? LIST)'()
(cons(car LIST)(cons(cdr LIST)'())))))
Unfortunately this just outputs the same list! Should be an easy fix I'm sure, and I know I'm close...Thanks for any help !
Upvotes: 7
Views: 4783
Reputation: 235984
The answer given by @davepmiller doesn't work ... Here's a correct implementation - you have to replace the first cons
with an append
for adding the first element at the end of the list.
(define (rotate-left LIST)
(if (null? LIST)
'()
(append (cdr LIST)
(cons (car LIST)
'()))))
(rotate-left '(a b c))
> '(b c a)
Upvotes: 9
Reputation: 17203
Test cases! Test cases! A check-expect here would have helped you understand the problem, and others to understand what you were looking for.
I think I'm getting old.
Upvotes: 1
Reputation: 2708
You got car and cdr backwards ! Here you go :
(define (rotate-left LIST)
(if(null? LIST)'()
(cons(cdr LIST)(cons(car LIST)'())))))
Upvotes: -2