0
votes

This procedure is supposed to return a list with alternative values from 3 given lists. So for example (alt ('a b c)'(1 2 3)'(i j k)) should return '(a 1 i b 2 j c 3 k).

This is my logic so far. I would take the first element of each list and recursively call the procedure again with cdr as the new arguments.

(define (alternate lst1 lst2 lst3)
    (cons (car lst1)
          (cons (car lst2)
                (cons (car lst3)
                (alternate (cdr lst1)(cdr lst2)(cdr lst3))))))

The error occurs in

(cons (car lst1)

"mcar: contract violation

expected: mpair?

given()"

(cons a d) returns a newly allocated pair whose first element is a and second element is d. But since there are 3 not 2 given lists, is there another way to approach creating lists?

Would this be another approach?

(define (alternate lst1 lst2 lst3)
    (list (car lst1)(car lst2)(car lst3))
        (alternate (cdr lst1)(cdr lst2)(cdr lst3)))
2

2 Answers

2
votes

You need to add empty list check to avoid the error. So your code should look like this:

(define (alternate lst1 lst2 lst3)
  (if (or (null? lst1) (null? lst2) (null? lst3))
      '()
      (cons (car lst1)
        (cons (car lst2)
          (cons (car lst3)
            (alternate (cdr lst1)(cdr lst2)(cdr lst3)))))))

If you can use SRFI-1 (or more precisely append-map), then you can also write like this:

(define (alt l1 l2 l3) (append-map list l1 l2 l3))
1
votes

You can just use the following standard Scheme:

(define (alternate . lists)
  (apply append (apply map list lists)))

Not very optimized, but does the job :)

Eval: http://eval.ironscheme.net/?id=175