开发者

How to make a list of arrays, not their symbols, in Lisp?

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.


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.


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

(map 'vector #'- p2 p1)

In your example, it returns:

#(2 2)


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜