Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipping lists together in Common Lisp - Problem with "and"

What I am trying to do is create a function zip (note now that this is not homework) that iterates through multiple lists simultaneously, applying a function to each list of elements, like so:

(zip f '(1 2 3) '(4 5 6) '(7 8 9)) = (list (f 1 4 7) (f 2 5 8) (f 3 6 9))
(zip f '(1 2 3 4) '(5 6) '(7 8 9)) = (list (f 1 5 7) (f 2 6 8))

Basically, it stops when any list runs out of elements. Here is my current attempt:

(defun zip (f &rest lists)
  (if (apply and lists) ; <- Here is where I think the problem is.
    (cons (apply f (mapcar #'car lists)) (zip f &rest (mapcar #'cdr lists)))
    nil))

I would like to know how fix the conditional statement to work with and, or something to that effect. I think the problem arises from and being a macro. I would also like to know if there is a built-in function for doing this already.

like image 754
Aaa Avatar asked Jun 01 '11 02:06

Aaa


People also ask

What is Lisp association list?

An association list, or a-list, is a data structure used very frequently in Lisp. An a-list is a list of pairs (conses); each pair is an association. The car of a pair is called the key, and the cdr is called the datum.

Why Lisp is called list processing?

The name LISP derives from "LISt Processor". Linked lists are one of Lisp's major data structures, and Lisp source code is made of lists.

How are list stored in Lisp?

In LISP, lists are constructed as a chain of a simple record structure named cons linked together.

What does cons do in Lisp?

In computer programming, cons (/ˈkɒnz/ or /ˈkɒns/) is a fundamental function in most dialects of the Lisp programming language. cons constructs memory objects which hold two values or pointers to two values. These objects are referred to as (cons) cells, conses, non-atomic s-expressions ("NATSes"), or (cons) pairs.


1 Answers

You are re-implementing mapcar

? (mapcar #'list '(1 2 3) '(4 5 6) '(7 8 9))
((1 4 7) (2 5 8) (3 6 9))
? (mapcar #'list '(1 2 3 4) '(5 6) '(7 8 9))
((1 5 7) (2 6 8))
? (mapcar #'+ '(1 2 3) '(4 5 6) '(7 8 9))
(12 15 18)
? (mapcar #'+ '(1 2 3 4) '(5 6) '(7 8 9))
(13 16)

BTW, the function you want in your code in place of all is and

like image 186
Doug Currie Avatar answered Sep 30 '22 15:09

Doug Currie