views:

230

answers:

1

Record syntax seems extremely convenient compared to having to write your own accessor functions. I've never seen anyone give any guidelines as to when it's best to use record syntax over normal data declaration syntax, so I'll just ask here.

+13  A: 

You should use record syntax in two situations:

  1. The type has many fields
  2. The type declaration gives no clue about its intended layout

For instance a Point type can be simply declared as:

data Point = Point Int Int deriving (Show)

It is obvious that the first Int denotes the x coordinate and the second stands for y. But the case with the following type declaration is different (taken from Learn You a Haskell for Great Good):

data Person = Person String String Int Float String String deriving (Show)

The intended type layout is: first name, last name, age, height, phone number, and favorite ice-cream flavor. But this is not evident in the above declaration. Record syntax comes handy here:

data Person = Person { firstName :: String  
                     , lastName :: String  
                     , age :: Int  
                     , height :: Float  
                     , phoneNumber :: String  
                     , flavor :: String  
                     } deriving (Show)

The record syntax made the code more readable, and saved a great deal of typing by automatically defining all the accessor functions for us!

Vijay Mathew
You also have an interesting use of record syntax in the `State` monad, where `runState` is used as a bit of syntactic cleverness.
jberryman