Dynamically-typed languages like Racket don’t have a need for a datatype-like structure to build one-of types like ML and other statically-typed languages do.
number? and string? to check which type each value possesses) are used instead of pattern matching.Example 1: In a list of strings and numbers, create a function that sums all the numbers in the list along with the sum of the lengths of every string in this list.
Example 2: Create a datatype exp that represents an arithmetic expression with 4 subtypes (Const, Add, Negate, Multiply) and a function that evaluates such an expression.
structs simplify the process of creating one-of compound types in Racket.
To define a struct named X with 2 fields value1 and value2, we can simply write
(struct X (value1 value2))
Defining a struct simultaneously defines functions that allow you to access its fields.
Type guards will also be simultaneously defined.
We can also supplement structs with the following attributes:
#:transparent (allows the implementation details of a given struct to be exposed whenever it is called in the REPL)#:mutable (provides more functions to support mutability)