Map Function

Discussion of Common Lisp
Post Reply
ktx
Posts: 3
Joined: Tue Dec 28, 2010 5:08 pm

Map Function

Post by ktx » Tue Dec 28, 2010 5:14 pm

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!

nuntius
Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: Map Function

Post by nuntius » Tue Dec 28, 2010 7:36 pm

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))))

Warren Wilkinson
Posts: 117
Joined: Tue Aug 10, 2010 11:24 pm
Location: Calgary, Alberta
Contact:

Re: Map Function

Post by Warren Wilkinson » Tue Dec 28, 2010 8:25 pm

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.

ktx
Posts: 3
Joined: Tue Dec 28, 2010 5:08 pm

Re: Map Function

Post by ktx » Wed Dec 29, 2010 4:22 am

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))

Warren Wilkinson
Posts: 117
Joined: Tue Aug 10, 2010 11:24 pm
Location: Calgary, Alberta
Contact:

Re: Map Function

Post by Warren Wilkinson » Wed Dec 29, 2010 11:35 am

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.

ktx
Posts: 3
Joined: Tue Dec 28, 2010 5:08 pm

Re: Map Function

Post by ktx » Wed Dec 29, 2010 11:47 am

Thanks Warren exactly what I wanted.

Post Reply