Arrays in Racket
Here’s the translation of the Go code example for arrays to Racket, along with explanations in Markdown format suitable for Hugo:
In Racket, we use vectors as the equivalent of arrays. Vectors are fixed-length sequences of elements that can be accessed and modified in constant time.
#lang racket
(define (main)
; Here we create a vector 'a' that will hold exactly 5 integers.
; In Racket, vectors are mutable and can hold any type of data.
(define a (make-vector 5 0))
(printf "emp: ~a\n" a)
; We can set a value at an index using vector-set!, and get a value with vector-ref.
(vector-set! a 4 100)
(printf "set: ~a\n" a)
(printf "get: ~a\n" (vector-ref a 4))
; The built-in vector-length function returns the length of a vector.
(printf "len: ~a\n" (vector-length a))
; Use this syntax to declare and initialize a vector in one line.
(define b (vector 1 2 3 4 5))
(printf "dcl: ~a\n" b)
; In Racket, we don't have a direct equivalent to Go's "..." syntax for counting elements.
; Instead, we can use quote to create a list and then convert it to a vector.
(set! b (list->vector '(1 2 3 4 5)))
(printf "dcl: ~a\n" b)
; Racket doesn't have a direct equivalent to Go's index-based initialization.
; We can achieve a similar result by creating a vector and then setting specific indices.
(set! b (make-vector 5 0))
(vector-set! b 0 100)
(vector-set! b 3 400)
(vector-set! b 4 500)
(printf "idx: ~a\n" b)
; To create multi-dimensional data structures, we can use vectors of vectors.
(define twoD (make-vector 2 (make-vector 3 0)))
(for ([i (in-range 2)])
(for ([j (in-range 3)])
(vector-set! (vector-ref twoD i) j (+ i j))))
(printf "2d: ~a\n" twoD)
; You can create and initialize multi-dimensional vectors at once too.
(set! twoD (vector (vector 1 2 3) (vector 1 2 3)))
(printf "2d: ~a\n" twoD))
(main)
Note that vectors appear in the form #(v1 v2 v3 ...)
when printed in Racket.
To run this program, save it as vectors.rkt
and use the racket
command:
$ racket vectors.rkt
emp: #(0 0 0 0 0)
set: #(0 0 0 0 100)
get: 100
len: 5
dcl: #(1 2 3 4 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))
In Racket, vectors are more flexible than arrays in some languages, as they can hold elements of different types. However, for performance-critical applications that require homogeneous data, Racket also provides typed vectors through its racket/vector
module.