Haskell by Example: Record Syntax
Defining data types with named fields through this code example showing record syntax declaration, auto-generated getter functions, record construction with field names, and immutable record updates creating new values.
Code
-- Define a Person using record syntax
data Person = Person {
firstName :: String,
lastName :: String,
age :: Int,
email :: String
} deriving (Show)
-- Create a record
alice :: Person
alice = Person {
firstName = "Alice",
lastName = "Smith",
age = 28,
email = "[email protected]"
}
-- Access fields (getter functions are auto-generated)
greet :: Person -> String
greet p = "Hello, " ++ firstName p
-- Update a field (creates a new record)
birthday :: Person -> Person
birthday p = p { age = age p + 1 }Explanation
Record syntax provides named fields for data constructors, improving readability and enabling order-independent construction compared to positional arguments. While standard ADTs use positional parameters like Person String String Int String, record syntax assigns names to each field, making code self-documenting and less error-prone when types are similar.
Defining a record automatically generates getter functions with the same names as the fields. The field declaration firstName :: String creates both a field in the data type and a function firstName :: Person -> String that extracts that field from a Person value. This eliminates manual accessor function definitions and ensures consistent naming conventions.
Record updates use special syntax record { field = newValue } to create modified copies. Since Haskell data is immutable, this doesn't modify the original object but returns a new record with specified fields changed and all other fields copied from the original. Multiple fields can be updated simultaneously by separating them with commas. This immutability ensures referential transparency and thread safety.
Code Breakdown
data Person = Person { ... } defines type and named fields.firstName = "Alice" order-independent field initialization.firstName p auto-generated getter function extracts field.p { age = age p + 1 } creates copy with updated age field.
