views:

116

answers:

5

I'm trying to make a function to get a delta between arrays, but right now just want to make a subset: get Nth element.

 (defvar p1 #(1 2))
 (defvar p2 #(3 4))
 (mapcar '(lambda (x) (aref x 0)) '(p1 p2))

 debugger invoked on a TYPE-ERROR in ...
   The value P1 is not of type ARRAY.

The same error if I make it with make-array.

How do I apply the lambda function, or how to apply (aref x 0), or (aref x N) in general case?

In the end I want to make a function that returns a delta: p2 - p1.

+1  A: 

I think the problem is that you have quoted the list, i.e.

'(p1 p2)

You should instead have

(list p1 p2)

because in your program you actually try to apply mapcar to a list containing two elements, the symbol p1 and the symbol p2.

antti.huima
A: 

antti.huima has it right. However, there is another error in your code:

(mapcar #'(lambda (x) (aref x 0)) (list p1 p2))

Note the hash mark before the single quote that precedes the lambda.

jkndrkn
+3  A: 

MAPCAR takes a function as first argument. '(lambda (x) (aref x 0)) is the same as (quote (lambda (x) (aref x 0))), and this is not a function. You want to make it a function with (function (lambda (x) (aref x 0))), which can be written shorter as #'(lambda (x) (aref x 0)), or even (because of a standard macro) (lambda (x) (aref x 0)).

'(p1 p2) is the same as (quote (p1 p2)). QUOTE means that the arguments are not evaluated, so the names "P1" and "P2" stand for themselves, not for their values. The type error you get is that the symbol 'P1 is not an array, it just has an array as value. In order to get a list of the values, use LIST: (list p1 p2).

In conclusion: (mapcar #'(lambda (x) (aref x 0)) (list p1 p2))

EDIT: For subtracting vectors, you should look into the MAP function; note that you can provide multiple sequences.

Svante
This answers the superficial problem without addressing the ultimate goal of getting the delta.
Xach
xach, I gave a hint in the last paragraph.
Svante
A: 

If you want to, you can use SYMBOL-VALUE:

(defvar p1 #(1 2))
(defvar p2 #(3 4))
(mapcar #'(lambda (x) (aref (symbol-value x) 0)) '(p1 p2))
perp
This won't work for anything but global values.
Xach
+3  A: 

To get a delta vector containing the difference between two vectors, try this:

(map 'vector #'- p2 p1)

In your example, it returns:

#(2 2)
Xach
That's what I hinted at.
Svante
a point from me gets you nearer the badge
Rainer Joswig