Sohal
Sohal

Reputation: 11

How to swap first two items of a list in racket?

I am trying to write a function that takes a list and returns the same list with its first two elements swapped for instance given '(a b c d e f) it should return '(b a c d e f), I have managed to return the first two items swapped however it puts the rest of the elements in a list '(b a (c d e f)),also is there a simple way of doing this other than how I have done it.

(define swap-two (λ (l)
                   (cond
                     ((empty? l) 0)
                     ((< (length l) 2) "less than two")
                     ((>= (length l) 2) (append (list (cadr l) (car l) (cddr l))))
                     (#t l))))

Upvotes: 0

Views: 1596

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

We can simplify the solution, for starters you don't need so many cases, either the list has >= 2 elements, or not.

In Racket we can leverage the intuitively named first and second procedures for obtaining the first and second elements in a list, and the elements after that can be obtained with the not-so-intuitive cddr procedure.

The last step is to just cons everything together, to build a proper list. You were using (append (list ...)), that's why the last part appeared inside a list. Better spend some time familiarizing yourself with how cons, list and append work. This is what I mean:

(define swap-two
  (λ (lst)
    (if (< (length lst) 2)
        "less than two"
        (cons (second lst)
              (cons (first lst)
                    (cddr lst))))))

It works as expected:

(swap-two '(a b c d e f))
=> '(b a c d e f)

Upvotes: 1

Related Questions