Question

Someone please help me with this function?

use scheme function that behaves like a recursive version of swap.

(reswap '((h i)(j k) l (m n o)))

should return

((k j) (i h) (n m o) l) ;

and

(reswap '((a b) c (d (e f)) g (h i)))

should return

(c (b a) g ((f e) d) (i h))) 
Was it helpful?

Solution

Try this:

(define (rswap lst)

  ;; Create a helper function to do the recursive work.
  (define (helper in out)

    ;; If the input is not a list, simply return it.
    ;; There is nothing to be done to rswap it.
    (if (not (list? in))
      in

      ;; If in is an empty list, simply return the out.
      (if (null? in)
        out

        ;; If in is a list with only one item, append
        ;; the result of calling rswap on the item to 
        ;; out and return it.
        (if (null? (cdr in))
          (append out (list (rswap (car in))))

          ;; This is where the recursion continues.
          ;; Take two items off in before the next call.
          ;; rswap the two items and add them to out.
          (helper
            (cddr in)
            (append out (list (rswap (cadr in)) (rswap (car in)))))))))

  (helper lst '()))

OTHER TIPS

Lol this looks like a good question but all I got was

(define (swap lst)
    ; if the list is empty or has a single element
    (cond ((or (null? lst) (null? (cdr lst)))
    ; then return that list
     lst)
    (else
    ; by first adding the second element
     (cons (cadr lst)
           (cons (car lst)
                 (swap (cddr lst)))))))

but that just does a normal swap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top