# [Maxima] interlacing lists

Stavros Macrakis macrakis at alum.mit.edu
Mon May 19 09:26:12 CDT 2008

```The Maxima function is easy enough:

il(a,b):=xreduce(append,map("[",a,b));

But you seem to be asking for a Lisp function, not a Maxima function?

(mapcan #'list a b) is not optimal, but fast enough for most purposes.

Writing out the do-loop for this is probably not worth it, but:

;; maybe slightly faster, but longer and more complicated
(defun il1 (a b)
(do ((res nil (list* (car b) (car a) res))
(a a (cdr a))
(b b (cdr b)))
((or (null a) (null b)) (nreverse res))))

;; optimal, but trickier and really not much faster in the end
(defvar il2-thing (list nil) "internal to il2")
(defun il2 (a b)
(let ((res (rplacd il2-thing nil)))
(do ((last res)
(a a (cdr a))
(b b (cdr b)))
((or (null a) (null b)) (cdr res))
(rplacd last (cons (car a)
(setq last (cons (car b) nil)))))))

Of course, whether this works for you depends what you want to do with
unequal-length lists: use the shortest (mapcan), give an error, fill
with some special value, etc.

-s

On Mon, May 19, 2008 at 9:06 AM, Barton Willis <willisb at unk.edu> wrote:
> Do we have a Maxima function that interlaces lists? By this I mean
>  (interlace-lists (list 1 2) (list 'a 'b)) ---> (list 1 'a 2 'b)
>
> This function is easy to write---I wrote my own, but I don't want to
> duplicate a function we already have (and I'm too lazy to look for it).
```

More information about the Maxima mailing list