Page 1 of 1

Map Function

Posted: Tue Dec 28, 2010 5:14 pm
by ktx
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!

Re: Map Function

Posted: Tue Dec 28, 2010 7:36 pm
by nuntius
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))))

Re: Map Function

Posted: Tue Dec 28, 2010 8:25 pm
by Warren Wilkinson
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))

Re: Map Function

Posted: Wed Dec 29, 2010 4:22 am
by ktx
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))

Re: Map Function

Posted: Wed Dec 29, 2010 11:35 am
by Warren Wilkinson
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)

Re: Map Function

Posted: Wed Dec 29, 2010 11:47 am
by ktx
Thanks Warren exactly what I wanted.