Question

Im trying to do the following in the list below: Let say list one consists of (1234) and list 2 is (5678) I am trying to print it in the following way (15263748) This is what I have for now but I am not sure where to go after this. Of course right now the code below prints it like 12 34 it should be 1 3 2 4

   (define (arrange-list lst1 lst2)
  (append lst1 lst2))
 (arrange-list '(12) '(34))
Was it helpful?

Solution

This is a common procedure, usually known as interleave. Assuming that the input lists have the same length, we can write the following implementation from scratch, using explicit recursion:

(define (interleave lst1 lst2)
  (if (null? lst1)
      '()
      (cons (car lst1)
            (interleave lst2 (cdr lst1)))))

The trick is taking one element from one list, and then from the other until both lists are exhausted. A more idiomatic solution in Racket would be to use built-in procedures, like this:

(define (interleave lst1 lst2)
  (flatten (map cons lst1 lst2)))

Either way it works as expected:

(interleave '(1 2 3 4) '(5 6 7 8))
=> '(1 5 2 6 3 7 4 8)

OTHER TIPS

If the lists aren't of equal length, this is my solution which works albeit is not as elegant as the one mentioned in the other answer.

Basically, we maintain a variable x while recursively calling the procedure that indicates which list needs processing currently. The first list is indicated by 1 and the second, 2.

(define (print-alt A B x)(cond
                ((and (null? A) (null? B)) '())                                                                                       
                 ((= 1 x) (cond
                           ((null? A) (print-alt A B 2))
                           (else (append (list (car A)) (print-alt (cdr A) B 2)))))
                (else (cond
                      ((null? B) (print-alt A B 1))
                      (else (append (list (car B)) (print-alt A (cdr B) 1)))))))

Here is the output:

(print-alt (list 1 2 3 4 5 6) (list 5 6 7 8 9 10 11 12 123) 1)
(1 5 2 6 3 7 4 8 5 9 6 10 11 12 123)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top