Reputation:
Say I have the following custom data type and function in Haskell:
data Person = Person { first_name :: String,
last_name :: String,
age :: Int
} deriving (Eq, Ord, Show)
If I want to create a function print_age
to print a Person's age, like so: print_age (Person "John" "Smith" 21)
, how would I write print_age
to access the age parameter? I'm an Object Oriented guy, so I'm out of my element here. I'm basically looking for the equivalent of Person.age.
Upvotes: 54
Views: 43450
Reputation: 102006
This is called record syntax, LYAH has a good section on it.
When a datatype is defined with records, Haskell automatically defines functions with the same name as the record to act as accessors, so in this case age
is the accessor for the age field (it has type Person -> Int
), and similarly for first_name
and last_name
.
These are normal Haskell functions and so are called like age person
or first_name person
.
Upvotes: 26
Reputation: 152682
In addition to the age
function mentioned in other answers, it is sometimes convenient to use pattern matching.
print_age Person { age = a } = {- the a variable contains the person's age -}
There is a pretty innocuous extension that allows you to skip the naming bit:
{-# LANGUAGE NamedFieldPuns #-}
print_age Person { age } = {- the age variable contains the person's age -}
...and another, viewed with varying degrees of distrust by various community members, which allows you to even skip saying which fields you want to bring into scope:
{-# LANGUAGE RecordWildCards #-}
print_age Person { .. } = {- first_name, last_name, and age are all defined -}
Upvotes: 12
Reputation: 183873
Function application is prefix, so age person
would correspond to the person.age()
common in OOP languages. The print_age
function could be defined pointfree by function composition
print_age = print . age
or point-full
print_age person = print (age person)
Upvotes: 71