BudiBadu Logo
Samplebadu

Haskell by Example: Algebraic Data Types

GHC 9.x

Defining custom data structures with multiple constructors through this code example showing sum type declaration with pipe separator, value constructors with parameters, pattern matching on constructors, and deriving Show for string conversion.

Code

-- Define a Shape type with three constructors
data Shape = Circle Float Float Float -- x, y, radius
           | Rectangle Float Float Float Float -- x1, y1, x2, y2
           | Point Float Float -- x, y
           deriving (Show)

-- Function to calculate area based on the shape
area :: Shape -> Float
area (Circle _ _ r) = pi * r ^ 2
area (Rectangle x1 y1 x2 y2) = abs (x2 - x1) * abs (y2 - y1)
area (Point _ _) = 0

-- Creating instances
myCircle :: Shape
myCircle = Circle 10 20 5

myRect :: Shape
myRect = Rectangle 0 0 10 10

Explanation

Algebraic Data Types (ADTs) are Haskell's primary mechanism for structuring data, defined using the data keyword followed by one or more value constructors separated by the pipe | symbol. Each constructor can hold different data fields with different types. This example defines a Shape type that can be a Circle, Rectangle, or Point, representing a sum type where a value is one variant OR another.

Value constructors behave like functions, taking parameters and returning values of the defined type. The Circle Float Float Float constructor is a function taking three floats and producing a Shape. Pattern matching on ADTs allows functions to handle each constructor case separately, with the compiler ensuring all cases are covered through exhaustiveness checking.

The deriving (Show) clause automatically generates code to convert custom types into strings for printing and debugging. Without this, attempting to print a Shape value would result in a compiler error. Other common derivable typeclasses include Eq for equality comparison, Ord for ordering, and Read for parsing strings into values.

Code Breakdown

2
Circle Float Float Float constructor function takes 3 floats, returns Shape.
5
deriving (Show) auto-generates string conversion for printing.
9
area (Circle _ _ r) pattern matches Circle, ignores position with wildcards.
15
Circle 10 20 5 calls constructor function to create Shape value.