🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Custom Types

A custom type is a new type that a program defines for its own values. The data keyword starts the definition.

A Circle value gives its area

The Circle constructor carries one Double, the radius. The area rule for Circle uses 3.14 as the circle constant.

data Shape = Circle Double | Rectangle Double Double

area :: Shape -> Double
area (Circle r) = 3.14 * r * r
area (Rectangle w h) = w * h

main :: IO ()
main = print (area (Circle 1))

A Rectangle value gives its area

The Rectangle constructor carries two Double values. The second area rule multiplies them.

data Shape = Circle Double | Rectangle Double Double

area :: Shape -> Double
area (Circle r) = 3.14 * r * r
area (Rectangle w h) = w * h

main :: IO ()
main = print (area (Rectangle 4 2.5))

Matching on the constructor picks a label

describe has one equation per constructor. The matching constructor decides which text comes back.

data Shape = Circle Double | Rectangle Double Double

describe :: Shape -> String
describe (Circle _) = "Round"
describe (Rectangle _ _) = "Four sides"

main :: IO ()
main = print (describe (Circle 9), describe (Rectangle 2 3))

Example

data Shape = Circle Double | Rectangle Double Double

area :: Shape -> Double
area (Circle r) = 3.14 * r * r
area (Rectangle w h) = w * h

totalArea :: [Shape] -> Double
totalArea shapes = sum (map area shapes)

main :: IO ()
main = print (totalArea [Circle 1, Rectangle 4 2.5])

Key points

  • Data declaration: data Shape = Circle Double | Rectangle Double Double defines a type named Shape.
  • Type name: Shape is the name of the new type, and it starts with a capital letter.
  • Constructors: Circle and Rectangle are constructors, the functions that build Shape values.
  • Alternatives: the | symbol separates the different ways to build a value of the type.
  • Fields: the types after a constructor name are the values that constructor carries.
  • Using a value: pattern matching on the constructor picks the rule that fits the value.

In this example, the data line defines Shape with two constructors. area matches on each constructor, so the circle gives 3.14 and the rectangle gives 10.0. totalArea maps area over the list and adds the results with sum. The printed total is 13.14.

Note

Shape values have no text form in this lesson, so programs print numbers and text computed from them.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

In data Shape = Circle Double | Rectangle Double Double, what is Circle?