Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 528
wecsam Avatar asked Jun 22 '12 20:06

wecsam


People also ask

How do I find the first element of a vector?

vector::front() This function can be used to fetch the first element of a vector container.

What is a vector in Scheme?

Vectors are heterogenous structures whose elements are indexed by exact non-negative integers. A vector typically occupies less space than a list of the same length, and the average time required to access a randomly chosen element is typically less for the vector than for the list.

How do I remove the first element of a vector?

To remove first element of a vector, you can use erase() function. Pass iterator to first element of the vector as argument to erase() function.


1 Answers

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.

like image 167
Óscar López Avatar answered Nov 15 '22 10:11

Óscar López