wecsam
wecsam

Reputation: 2751

Get first element in vector in Scheme

Let's say that I create a vector/array in Scheme:

(let* ((x #(1 2 3)))
  (list-ref x 0)) ; returns error 

What syntax or function can I use in the place of that list-ref to get 1?

EDIT: I'm using Script-Fu with GIMP 2.8, where array-ref doesn't seem to work.

Upvotes: 6

Views: 2860

Answers (2)

Óscar López
Óscar López

Reputation: 236004

The expression(define v '#(1 2 3)) is shorthand for creating a new vector, in standard Scheme it's equivalent to this:

(define v (list->vector '(1 2 3)))

Or this:

(define v (make-vector 3))
(vector-set! v 0 1)
(vector-set! v 1 2)
(vector-set! v 2 3)

Once a vector is created (using any of the mentioned procedures), the correct way to access an element in a vector is by calling the vector-ref procedure - clearly, because it's a vector and not a list of elements:

(vector-ref v 0)

In the previous expression, v is the vector and 0 the index whose element we want to retrieve. Take a look at the documentation for a more detailed explanation of the procedures outlined above.

Upvotes: 9

Justin Ethier
Justin Ethier

Reputation: 134157

You can use vector-ref for this purpose. For example:

(vector-ref x 0)

Here is a link to the R5RS spec's section on vectors, which provides more information.

Upvotes: 4

Related Questions