Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This method traverses the list at most twice:</p> <pre><code>(define (swap-index index1 index2 lst) ;; FIND-ELEMENTS -- ;; INPUT: count, an integer; lst, a list ;; OUTPUT: a pair of the form '(a . b) (define (find-elements count lst) (cond ((null? lst) '()) ; really, we should never reach this if indices are valid ((= count index1) ; found the first element, so hold on to it while we look for the next one (cons (car lst) (find-elements (+ 1 count) (cdr lst)))) ((= count index2) (car lst)) ; found the second element, return part 2 of the pair (else ; since we only care about 2 elements we can just skip everything else (find-elements (+ 1 count) (cdr lst))))) ;; BUILD-LIST -- ;; INPUT: count, an integer; elements, a pair; lst, a list ;; OUTPUT: a new list (define (build-list count elements lst) (cond ((null? lst) '()) ; again, we shouldn't get here if indices are valid ((= count index1) ; reached first index, substitute 2nd element and keep going (cons (cdr elements) (build-list (+ 1 count) elements (cdr lst)))) ((= count index2) ; reached second index, substitute 1st element and stop (cons (car elements) (cdr lst))) (else ; everything else just gets added to the list per usual (cons (car lst) (build-list (+ 1 count) elements (cdr lst)))))) (build-list 0 (find-elements 0 lst) lst)) ; call build-list using a call to find-elements as a parameter </code></pre> <p>First, <code>find-elements</code> looks through the list and returns a <code>cons</code>'d pair of the elements that we want to swap. <strong>Note:</strong> this code depends on the assumption that the indices are given in order so that the smallest is first.</p> <p>Next, <code>build-list</code> takes the output from <code>find-elements</code> so that during our next traversal we can substitute the appropriate element.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload