Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing members of a custom data type in Haskell

Tags:

haskell

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)

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.


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 -}