Variables in Racket

Our first program will demonstrate variable declaration and initialization in Racket. Here’s the full source code:

#lang racket

; Define and initialize a variable
(define a "initial")
(displayln a)

; Define multiple variables at once
(define-values (b c) (values 1 2))
(displayln (format "~a ~a" b c))

; Racket infers types automatically
(define d #t)
(displayln d)

; Variables without initialization are undefined
(define e (void))
(displayln e)

; Define and initialize in one step
(define f "apple")
(displayln f)

In Racket, variables are declared using the define keyword. Here’s a breakdown of the code:

  1. We use define to declare and initialize a variable a with the string “initial”.

  2. Multiple variables can be declared and initialized at once using define-values.

  3. Racket is dynamically typed, so it automatically infers the type of variables.

  4. Variables declared without initialization are undefined. In Racket, we can use (void) to represent this concept.

  5. There’s no special syntax for declaration and initialization in one step in Racket, as define already serves this purpose.

To run the program, save the code in a file (e.g., variables.rkt) and use the racket command:

$ racket variables.rkt
initial
1 2
#t
#<void>
apple

Racket doesn’t have a separate compilation step like some other languages. The racket command both compiles and runs the program in one step.

Now that we’ve explored basic variable usage in Racket, let’s continue learning about other aspects of the language.