Map Function
Map Function
I have two lists, I want to apply a function to the first element of the list1 with each element in list2, then the second item in the list1 with each item in the list2, etc. I assume the map function would be the best way to do this but have no idea how to call some sort of loop function with one item at a time from list1. For example:
listx (1 2 3 4 5)
listy (6 7 8 9 10)
function add
add 1 6
add 1 7
add 1 8
add 1 9
add 1 10
add 2 6
add 2 7
etc...
Is mapping the best way to do this? Could you provide me with some other websites/information?
Thanks!
listx (1 2 3 4 5)
listy (6 7 8 9 10)
function add
add 1 6
add 1 7
add 1 8
add 1 9
add 1 10
add 2 6
add 2 7
etc...
Is mapping the best way to do this? Could you provide me with some other websites/information?
Thanks!
Re: Map Function
Here's one direct approach.
Code: Select all
(dolist (x (list 1 2 3 4 5))
(dolist (y (list 6 7 8 9 10))
(print (list x y))))
-
- Posts: 117
- Joined: Tue Aug 10, 2010 11:24 pm
- Location: Calgary, Alberta
- Contact:
Re: Map Function
nuntius has the right idea. This task is a lot like computing the cross product, here is a function I whipped up.
Code: Select all
(defun cross (fn alist blist) (mapcar #'(lambda (a) (mapcar #'(lambda (b) (funcall fn a b)) blist)) alist))
(cross #'* '(1 2 3) '(1 2 3)) ;; gives ((1 2 3) (2 4 6) (3 6 9))
Need an online wiki database? My Lisp startup http://www.formlis.com combines a wiki with forms and reports.
Re: Map Function
Would there be a way to run either function and create one list for the output instead of multiple sub-lists?
i.e. (1 2 3 2 4 6 3 6 9) not ((1 2 3) (2 4 6) (3 6 9))
i.e. (1 2 3 2 4 6 3 6 9) not ((1 2 3) (2 4 6) (3 6 9))
-
- Posts: 117
- Joined: Tue Aug 10, 2010 11:24 pm
- Location: Calgary, Alberta
- Contact:
Re: Map Function
Use mapcan for the outer mapping function.
Code: Select all
(defun cross (fn alist blist) (mapcan #'(lambda (a) (mapcar #'(lambda (b) (funcall fn a b)) blist)) alist))
(cross #'* '(1 2 3) '(1 2 3)) ;; gives (1 2 3 2 4 6 3 6 9)
Need an online wiki database? My Lisp startup http://www.formlis.com combines a wiki with forms and reports.
Re: Map Function
Thanks Warren exactly what I wanted.