7

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 !

Óscar López
  • 232,561
  • 37
  • 312
  • 386
Don Johnson
  • 93
  • 1
  • 6
  • Will the input list never be nested? If it can be nested, do you want the nesting entirely preserved in the output or should the output be flat? If the input can be nested, should the first s-expression be rotated or the first atom? Problems have to be well specified, particularly the assumptions that can be made about the input and the requirements of the output. – itsbruce Oct 24 '12 at 14:19
  • Is there a reason why you're using list representation here? This kind of problem seems well suited for a cyclic data structure, so that the rotation is implied by just walking through the structure. More information please! In what context do you need this operation? – dyoo Oct 24 '12 at 20:32

3 Answers3

9

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)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

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.

John Clements
  • 16,895
  • 3
  • 37
  • 52
-2

You got car and cdr backwards ! Here you go :

(define (rotate-left LIST)
    (if(null? LIST)'()
        (cons(cdr LIST)(cons(car LIST)'())))))
davepmiller
  • 2,620
  • 3
  • 33
  • 61
  • 1
    I guess you need to flatten the resulting list as well - `(define (rotate-left LIST) (flatten (cons (cdr LIST) (car LIST))))` – Ankur Oct 24 '12 at 12:01
  • @DonJohnson did you actually _test_ this answer? because it doesn't work, you know ... even after fixing the compilation problem, `(rotate-left '(a b c))` is returning `'((b c) a)`. Take a look at my answer for a working solution. – Óscar López Oct 24 '12 at 14:35
  • @Ankur good spot, although it assumes the function spec requires that the input list always be flat. If the input list is allowed to be nested, you should use append instead. – itsbruce Oct 24 '12 at 15:07