Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use record syntax for data declarations in Haskell?

Tags:

types

haskell

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.

like image 925
Rayne Avatar asked Nov 26 '09 07:11

Rayne


People also ask

What is record syntax in Haskell?

Basic Syntax Records are an extension of sum algebraic data type that allow fields to be named: data StandardType = StandardType String Int Bool --standard way to create a product type data RecordType = RecordType -- the same product type with record syntax { aString :: String , aNumber :: Int , isTrue :: Bool }

How do you declare types in Haskell?

Haskell has three basic ways to declare a new type: The data declaration, which defines new data types. The type declaration for type synonyms, that is, alternative names for existing types. The newtype declaration, which defines new data types equivalent to existing ones.

What is the difference between type and data in Haskell?

Type and data type refer to exactly the same concept. The Haskell keywords type and data are different, though: data allows you to introduce a new algebraic data type, while type just makes a type synonym. See the Haskell wiki for details.


1 Answers

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!

like image 125
Vijay Mathew Avatar answered Nov 10 '22 22:11

Vijay Mathew