Algebraic data types (ADTs) in Haskell are a way to construct complex and structured data types using simpler ones. They are called "algebraic" because they have a close analogy with algebraic expressions. ADTs can be understood as the combination of two concepts: sum types and product types.
Sum types (also called tagged unions or variant types) are data types that represent a choice between two or more alternatives. It loosely corresponds to “or” in algebraic expressions.
Product types are data types that group multiple values together. They are similar to records, structs, or tuples in other languages. Product types loosely correspond to “and” in algebraic expressions.
First, let’s see a simple example of an algebraic data type:
data Bool = True | False
Here, ‘Bool‘ is an algebraic data type with two data constructors, ‘True‘ and ‘False‘. This is an example of a sum type, as a value of the ‘Bool‘ type can be either ‘True‘ or ‘False‘.
Now, let’s take a look at a more complex example, which involves both sum types and product types:
data Shape = Circle Double
| Rectangle Double Double
| Triangle Double Double Double
In this case ‘Shape‘ is an algebraic data type representing geometric shapes. It consists of a sum type (‘Circle‘, ‘Rectangle‘, and ‘Triangle‘). Each data constructor is associated with a product type represented by the tuple of arguments:
- ‘Circle‘ takes one ‘Double‘ argument as the radius.
- ‘Rectangle‘ takes two ‘Double‘ arguments as width and height.
- ‘Triangle‘ takes three ‘Double‘ arguments as the lengths of its sides.
Now let’s define a function to compute the perimeter of a ‘Shape‘:
perimeter :: Shape -> Double
perimeter (Circle r) = 2 * pi * r
perimeter (Rectangle w h) = 2 * (w + h)
perimeter (Triangle a b c) = a + b + c
The ‘perimeter‘ function uses pattern matching to destructure the ‘Shape‘ and compute the perimeter accordingly.
Here’s a quick summary of algebraic data types in Haskell:
- ADTs consist of sum types and product types.
- Sum types represent a choice between two or more alternatives.
- Product types group multiple values together.
- ADTs are a powerful way to represent complex structured data, and they are fundamental in functional programming and type systems.