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:
We use
defineto declare and initialize a variableawith the string “initial”.Multiple variables can be declared and initialized at once using
define-values.Racket is dynamically typed, so it automatically infers the type of variables.
Variables declared without initialization are undefined. In Racket, we can use
(void)to represent this concept.There’s no special syntax for declaration and initialization in one step in Racket, as
definealready 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>
appleRacket 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.