Page 1 of 1

### Computing two dimensional functions

Posted: Thu May 14, 2009 10:36 pm
How one can write a function "map2D" that will be a 2-dimensional equivalent of the standard "map" function?

In other words, I like it to work like in the following example:

Line:

Code: Select all

``(map2D + '((1 . 2) (3 . 4) (5 . 6)) )``
should return a result:

Code: Select all

``(3 7 11)``
because:
1 + 2 = 3, or equivalently:

Code: Select all

``(+ 1 2) == 3``
3 + 4 = 7, or equivalently:

Code: Select all

``(+ 3 4) == 7``
5 + 6 = 11, or equivalently:

Code: Select all

``(+ 5 6) == 11``
Here "+" is acting like a function of two variables that is acting of every pair from the given list.

### Re: Computing two dimensional functions

Posted: Fri May 15, 2009 11:27 am
Edit: being an idiot.. it is talking about Scheme not CL :/ (salvaged this)

If you have a function that collects output of a function for each element of a list, mapcar, then:(untested)

Code: Select all

``````(defun fun-with-list-to-args (fun)
(lambda (list) (apply fun list)))
;;Now should work:
(mapcar (fun-with-list-to-args +) '((1 2) (3 4 5) (-1 1 -1 1)))
``````
, then the elements of the list should themselves be regular lists. (the '.' doesn't seem like a good idea to me.)

### Re: Computing two dimensional functions

Posted: Sun May 17, 2009 3:55 am
Thanks for your solution. But is there any way to change it, so it will work with lists of pairs (with dot inside)? (I cannot change the way in which input is passed to the function.)

### Re: Computing two dimensional functions

Posted: Sun May 17, 2009 6:39 am
blooper wrote:Thanks for your solution. But is there any way to change it, so it will work with lists of pairs (with dot inside)? (I cannot change the way in which input is passed to the function.)
A list with 2 elements with a "dot inside" is just a cons cell. You access the first element using the function car and the second element using cdr. So you need to write a function like this:

(lambda (cons-cell)
(+ (car cons-cell) (cdr cons-cell)))

and apply this function to every element of the list.

### Re: Computing two dimensional functions

Posted: Wed May 20, 2009 6:34 am
Thanks for the hint, but I still can't write the appropriate function. Scheme seems to be too abstract for me...

But thank you anyway. ### Re: Computing two dimensional functions

Posted: Wed May 20, 2009 8:26 am
blooper wrote:Thanks for the hint, but I still can't write the appropriate function. Scheme seems to be too abstract for me...
It is just a matter of using map with the function I wrote. Try this:

Code: Select all

``````(map
(lambda (cons)
(+ (car cons) (cdr cons)))
'((1 . 2) (3 . 4) (5 . 6)))``````
You will see that this returns exactly what should be returned by map2d in your example. It should be very easy to generalize this to accept all kinds of functions.