UP | HOME

Algebraic Data Type

Table of Contents

Algebraic Data Type is a composite type, we create them by combining other types and define the shape of each elements.

There are two popular types: Sum Type and Product Type.

1 Sum Type

Is an alternative type, where the type of a value will be one of many other types A | B. aka Union Type somewhere else.

data TrafficLight = Red | Yellow | Green

shouldGo :: TrafficLight -> Bool
shouldGo Red = False
shouldGo Yellow = True
shouldGo Green = True

main = print $ shouldGo Red

2 Product Type

Is a combination of many other types, usually have a tag assigned for pattern matching purpose.

data Rect a = Rect a a deriving Show

square :: Int -> Rect Int
square w = Rect w w

shapeA = square 5

main = print $ shapeA

Date: 2019-03-07 Thu 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41