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.
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.
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.
In LISP, lists are constructed as a chain of a simple record structure named cons linked together.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With