Maps in Racket

Maps in Racket

Maps are data structures that associate keys with values. In Racket, this functionality is provided by the hash form, which allows for the creation and manipulation of hash tables.

Creating an empty map

To create an empty hash table, you can use the make-hash function.

#lang racket

(define m (make-hash))

Setting key/value pairs

Set key/value pairs using the hash-set! function.

(hash-set! m "k1" 7)
(hash-set! m "k2" 13)

Printing a map

To display the contents of a hash table, use the hash function in combination with display.

(displayln (hash->list m))

Accessing values

Get a value for a key using the hash-ref function.

(define v1 (hash-ref m "k1"))
(displayln (format "v1: ~a" v1))

If the key doesn’t exist, the zero value (for numbers, this is 0) is returned, or you can provide a default value.

(define v3 (hash-ref m "k3" 0))
(displayln (format "v3: ~a" v3))

Getting the number of key/value pairs

The hash-count function returns the number of key/value pairs in a hash table.

(displayln (format "len: ~a" (hash-count m)))

Deleting key/value pairs

The hash-remove! function removes key/value pairs from a hash table.

(hash-remove! m "k2")
(displayln (hash->list m))

Clearing the map

To remove all key/value pairs, use the clear-hash function.

(hash-clear! m)
(displayln (hash->list m))

Checking for key presence

The optional third return value when getting a value from a hash table indicates if the key was present. This can be used to disambiguate between missing keys and keys with zero values.

(define-values (v2 prs) (hash-ref m "k2" (void)))
(displayln (format "prs: ~a" prs))

Declaring and initializing a new map

You can declare and initialize a new hash table in the same line with the hash function.

(define n (hash "foo" 1 "bar" 2))
(displayln (hash->list n))

Using utility functions

Racket’s racket/hash library contains several utility functions for hash tables.

(require racket/hash)

(define n2 (hash "foo" 1 "bar" 2))
(if (equal? n n2)
  (displayln "n == n2"))

Example Output

When you run the program, you should see the following output:

(("k1" . 7) ("k2" . 13))
v1: 7
v3: 0
len: 2
(("k1" . 7))
()
prs: #f
(("foo" . 1) ("bar" . 2))
n == n2

Next example: Functions.