Maps in Racket
On this page
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.
Setting key/value pairs
Set key/value pairs using the hash-set!
function.
Printing a map
To display the contents of a hash table, use the hash
function in combination with display
.
Accessing values
Get a value for a key using the hash-ref
function.
If the key doesn’t exist, the zero value (for numbers, this is 0
) is returned, or you can provide a default value.
Getting the number of key/value pairs
The hash-count
function returns the number of key/value pairs in a hash table.
Deleting key/value pairs
The hash-remove!
function removes key/value pairs from a hash table.
Clearing the map
To remove all key/value pairs, use the clear-hash
function.
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.
Declaring and initializing a new map
You can declare and initialize a new hash table in the same line with the hash
function.
Using utility functions
Racket’s racket/hash
library contains several utility functions for hash tables.
Example Output
When you run the program, you should see the following output:
Next example: Functions.