Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a string in lisp is a vector, why can't I access the first element using svref?

So, I'm trying to learn Lisp, and I've come across a problem in the definition of what a String is.

I'm reading the ANSI Common Lisp by Paul Graham, and in this book it states that a String is a vector, or one-dimensional Array.

So, I create a String:

(defvar *my-string* "abc")

And then I can access the first value of my-string this way:

(aref *my-string* 0)

But if it is a vector, why can't I access that element this way:

(svref *my-string* 0)

I mean, when I create a vector this way:

(defvar my-vec (make-array 4 :initial-element 1))

I can access first element using svref:

(svref my-vec 0) ; returns 1

I forgot to add error when I try svref on String:

"The value "abc" is not of type (SIMPLE-ARRAY T (*))."

like image 418
Arash Saidi Avatar asked Oct 02 '14 15:10

Arash Saidi


2 Answers

String is a vector, but it isn't a simple-vector. svref takes a simple-vector as first argument.

You can check it by calling:

(vector-p *my-string*)

which returns true

Unlike:

(simple-vector-p *my-string*)

which returns false.

Notice that (simple-vector-p my-vec) will return true as well, which confirms that make-array creates a simple-vector.

like image 198
soulcheck Avatar answered Nov 22 '22 19:11

soulcheck


soulcheck's answer is absolutely right, but it's worth the time to become comfortable with the HyperSpec. For instance, if you start at the page for svref, there's a note at the bottom:

Notes:

svref is identical to aref except that it requires its first argument to be a simple vector.

The glossary entry for simple vector (linked above) says:

simple vector n. a vector of type simple-vector, sometimes called a "simple general vector." Not all vectors that are simple are simple vectors—only those that have element type t.

15.2 The Arrays Dictionary is also helpful here, as is 15. Arrays as a whole.

like image 22
Joshua Taylor Avatar answered Nov 22 '22 19:11

Joshua Taylor