In common lisp, is there any difference to create a vector using '#(...) or just #(...)?

Viewed 121

In Common Lisp (SBCL), it is possible to create vectors (arrays) using ' before the # or not:

CL-USER> '#(a b c)
#(A B C)

CL-USER> #(a b c)
#(A B C)

Apparently, they seem to generate the same object. After using type-of and describe on these expressions, they return identical information:

CL-USER> (type-of #(a b c))
(SIMPLE-VECTOR 3)
CL-USER> (type-of '#(a b c))
(SIMPLE-VECTOR 3)
CL-USER> (describe #(a b c))
#(A B C)
  [simple-vector]

Element-type: T
Length: 3
; No value
CL-USER> (describe '#(a b c))
#(A B C)
  [simple-vector]

Element-type: T
Length: 3
; No value

Equality is also the same (with equalp):

CL-USER> (equalp '#(a b c) #(a b c))
T

But differs wit equal:

CL-USER> (equal '#(a b c) #(a b c))
NIL

The ' is not the responsible for the above result being NIL:

CL-USER> (equal '#(a b c) '#(a b c))
NIL

Is there any practical consequences of using one approach instead of the other when creating arrays?

Thanks.

1 Answers

quoting

To clear any confusion, '#(a b c) starts with an apostrophe, which quotes a value; this is the same as having (quote #(a b c)). Quoting evaluates as the literal value being quoted.

CL-USER> '3
3
CL-USER> 'a
A
CL-USER> '#(a b c)
#(a b c)

literals

Generally, quoting an expression and evaluating it does not give the same value. For example:

CL-USER> (equalp '(vector 1) (vector 1))
NIL

Above, '(vector 1) evaluates as a list of two values (a symbol and a number), but (vector 1) as a vector of one element.

For literal values, however, they have the same value whether they are quoted or not:

CL-USER> (= '3 3)
T

The literal vector #(a b c) behaves the same, it is self-evaluating. When the form is read, the reader creates a vector object. Such an object evaluates as itself:

CL-USER> (eval #(a b c))
#(a b c)

equal

The use of equal can be surprising here, but the result is consistent with the definition:

Two arrays are equal only if they are eq, with one exception: strings and bit vectors are compared element-by-element (using eql).

Here you don't manipulate strings or bit-vectors, so you only test for identity, as-if you used EQ. But you have two different instances of the vector, once quoted, once not quoted, and they are likely to be two distinct vectors (but EQ (and so, EQUAL too) could be T with a different compiler).

conclusion

Is there any practical consequences of using one approach instead of the other when creating arrays?

I don't think so, you generally don't quote numbers, the same goes for array literals.

NB. as for all literal values, you should not mutate them, they are constant values.

Related