Arrays in Scheme

In Scheme, a vector is similar to an array in other languages. It’s a fixed-size sequence of elements. Let’s explore how to work with vectors in Scheme.

(define (main)
  ; Create a vector of 5 elements, initially all set to 0
  (define a (make-vector 5 0))
  (display "emp: ") (display a) (newline)

  ; Set a value at an index
  (vector-set! a 4 100)
  (display "set: ") (display a) (newline)
  (display "get: ") (display (vector-ref a 4)) (newline)

  ; Get the length of the vector
  (display "len: ") (display (vector-length a)) (newline)

  ; Create and initialize a vector in one line
  (define b #(1 2 3 4 5))
  (display "dcl: ") (display b) (newline)

  ; Create a vector with specific elements
  (define c (vector 100 0 0 400 500))
  (display "idx: ") (display c) (newline)

  ; Create a 2D vector (vector of vectors)
  (define twoD (vector (vector 0 1 2) (vector 1 2 3)))
  (display "2d: ") (display twoD) (newline)

  ; Create and initialize a 2D vector at once
  (define twoD-2 #(#(1 2 3) #(1 2 3)))
  (display "2d: ") (display twoD-2) (newline))

(main)

Here’s an explanation of the Scheme code:

  1. We use make-vector to create a vector of a specific length, initially filled with zeros.

  2. vector-set! is used to set a value at a specific index, and vector-ref is used to get a value.

  3. vector-length returns the length of a vector.

  4. We can create and initialize a vector in one line using the #(...) syntax.

  5. Scheme doesn’t have a built-in way to create vectors with specific indices filled. We simulate this by creating a vector with the desired values.

  6. For multi-dimensional vectors, we create vectors of vectors.

  7. We can also create and initialize multi-dimensional vectors at once using nested #(...) syntax.

When you run this program, you should see output similar to this:

emp: #(0 0 0 0 0)
set: #(0 0 0 0 100)
get: 100
len: 5
dcl: #(1 2 3 4 5)
idx: #(100 0 0 400 500)
2d: #(#(0 1 2) #(1 2 3))
2d: #(#(1 2 3) #(1 2 3))

Note that vectors in Scheme are displayed in the form #(v1 v2 v3 ...) when printed.