Structs in Haskell

Our example demonstrates the use of structs, which are typed collections of fields useful for grouping data together to form records.

-- Define a data type `Person` with fields `name` and `age`.
data Person = Person { name :: String, age :: Int } deriving (Show)

-- `newPerson` function constructs a new `Person` with a given name and a fixed age.
newPerson :: String -> Person
newPerson name = Person name 42

main :: IO ()
main = do
    -- Creating a new `Person` with positional arguments.
    print (Person "Bob" 20)

    -- Creating a new `Person` with named fields.
    print (Person { name = "Alice", age = 30 })

    -- Field `age` omitted will be zero-valued.
    print (Person { name = "Fred" })

    -- Using the `newPerson` function to create a `Person`
    print (newPerson "Jon")

    -- Accessing a struct field.
    let s = Person { name = "Sean", age = 50 }
    print (name s)

    -- Structs in Haskell are immutable, but you can create a new struct with updated fields.
    let sp = s { age = 51 }
    print (age sp)

    -- Anonymous struct type for a single value.
    let dog = ( "Rex", True )
    print dog

To run the program, save the code in a file named Structs.hs and use:

$ runhaskell Structs.hs

The output will be:

Person {name = "Bob", age = 20}
Person {name = "Alice", age = 30}
Person {name = "Fred", age = 0}
Person {name = "Jon", age = 42}
"Sean"
50
51
("Rex",True)

Now that we can run basic Haskell programs, let’s learn more about the language.