Data Types and Structures in Racket | Schema Programming Part 3
Understanding data structures is crucial for any programming language, and Racket is no exception. In this part of our series, we will dive deep into Racket's core data types, starting from simple atoms to complex structured data.
Advertisement
Atomic Data Types
Racket has several "atomic" data types—data that isn't built out of other data.
1. Booleans
Booleans represent truth values. Racket uses #t for true and #f for false.
#t ; True
#f ; False
(boolean? #t) ; Returns #t
2. Numbers
Racket supports various number types, including integers, rationals, and complex numbers.
42 ; Integer
3.14 ; Real (Inexact)
1/2 ; Rational (Exact)
1+2i ; Complex
3. Symbols
Symbols are like strings but are interned, meaning two identical symbols refer to the same object in memory. They start with a quote '.
'my-symbol
(symbol? 'my-symbol) ; #t
(eq? 'a 'a) ; #t (efficient comparison)
4. Strings
Strings are sequences of characters enclosed in double quotes.
"Hello, Racket!"
(string-length "Hello") ; 5
Pairs and Lists
The most iconic structure in Lisp-family languages is the List, which is built from Pairs (or "Cons Cells").
Cons Cells (Pairs)
A pair is created using cons. It holds two values.
(cons 1 2)
; Result: '(1 . 2) - This is a "dotted pair"
To extract values, we use car (first) and cdr (rest).
(define p (cons 10 20))
(car p) ; 10
(cdr p) ; 20
Lists
A list is essentially a chain of pairs ending with an empty list '().
(cons 1 (cons 2 (cons 3 '())))
; Result: '(1 2 3)
Racket provides a shorthand list function:
(list 1 2 3) ; Same as '(1 2 3)
Advertisement
Common List Operations
- first: Returns the first element (same as
car). - rest: Returns the list without the first element (same as
cdr). - length: Returns the number of elements.
- null?: Checks if a list is empty.
(define my-list '(10 20 30))
(first my-list) ; 10
(rest my-list) ; '(20 30)
(empty? '()) ; #t
Creating Custom Structures
For more complex data, lists can be clumsy. Racket provides define-struct (or just struct in modern Racket) to define custom data types.
(define-struct point (x y))
(define p1 (make-point 5 10))
(point-x p1) ; 5
(point-y p1) ; 10
(point? p1) ; #t
When you define a struct name, Racket automatically generates:
make-name: Constructorname?: Predicatename-field: Accessors for each field
Summary
You've now mastered the building blocks of Racket data:
- Atoms: Numbers, Booleans, Symbols.
- Cons/Lists: The backbone of functional data organization.
- Structs: For creating your own data types.
In the next part, we will explore Control Flow, where we'll learn how to make decisions and control execution in Racket.
What function is used to create a pair in Racket?
Md Nasim Sheikh
Software Developer at softexForge