1

Ultimately, i shall be trying to reimplement sorting algorithms in scheme for linked lists. I have written a subprocedure that will help me along the way. The goal is to simply swap 2 elements, given as arguments "pair1 and pair2" and then return the list.

(define (cons-til lst until)
(cond
((or (null? lst) (eq? (car lst) until)) '())
(else (cons (car lst) (cons-til (cdr lst) until)))))

(define (swap lst pair1 pair2)
(cons (cons (append (cons-til lst (car pair1))
      (car pair2)) (car pair1)) (cdr pair2)))

(define my-list '(1 2 3 4 5 6 7))

(swap my-list (cdr (cdr my-list)) (cdr (cdr (cdr my-list))))

When the code is executed, it returns:

(((1 2 . 4) . 3) 5 6 7)

How can i fix this in order to have a plain scheme list. The element seems to have swapped correctly.

TomatoFarmer
  • 463
  • 3
  • 13

2 Answers2

2

Two suggestions:

  • Do you really want to write n cdr calls to index the nth element? I recommend strongly using integer indexes (if you need them, that is).

  • Referring to elements by index in a linked list (i. e. “random access”) is not very efficient most of the time, especially when done in loops. I strongly recommend using either vectors or a better suited algorithm that doesn't need random access, e. g. merge sort.

Svante
  • 50,694
  • 11
  • 78
  • 122
0
   (define (swap2 lst pair1 pair2)
   (append (append (append (cons-til lst (car pair1))
                  (list (car pair2)))
              (list (car pair1))) (cdr pair2)))

This code seems to work. I'm not sure this is completely efficient or a smart solution to the problem. Looking forward to other suggestions. The value given back is '(1 2 4 3 5 6 7)

TomatoFarmer
  • 463
  • 3
  • 13
  • 2
    I'm about to post exactly this code. But note that it is in fact wrong if you have duplicate elements. For example, try `(define my-list '(1 2 1 4 5 6 7))`. Also, you are right that it's not efficient. Swapping is an efficient operation on random access data structure (e.g., array, also known as vector in Racket), but very inefficient for lists. – Sorawee Porncharoenwase Jan 25 '19 at 10:42