Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a list to the left in Scheme/Racket

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 !

like image 718
Don Johnson Avatar asked Oct 24 '12 09:10

Don Johnson


Video Answer


2 Answers

The answer given by @laser_wizard 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)
like image 83
Óscar López Avatar answered Sep 28 '22 03:09

Óscar López


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.

like image 41
John Clements Avatar answered Sep 28 '22 03:09

John Clements