[plt-scheme] "Zipping" two lists?

From: Eli Barzilay (eli at barzilay.org)
Date: Wed Feb 22 13:33:19 EST 2006

On Feb 22, Greg Woodhouse wrote:
> Does Scheme provide a standard way to do this? I wrote a little ad hoc
> function, but it seems that this ought to be common enough an operation
> to have a standard solution.
> 
> ;;zip two list (e.g., (zip (1 2) (3 4)) is ((1 3) (2 4)))
> ;;(list, list) -> list
> (define (zip ls1 ls2)
>   (if (equal? (length ls1) (length ls2))
>       (if (null? ls1) '()
>           (cons (list (car ls1) (car ls2))
>                 (zip (cdr ls1) (cdr ls2))))))

| > (map list '(1 2) '(3 4))
| ((1 3) (2 4))

So:

| > (define (zip . lists) (apply map list lists))
| > (zip '(1 2) '(3 4))
| ((1 3) (2 4))

(I've seen people compare this to the formula with pi, i, and e...)

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!


Posted on the users mailing list.