Algebraic Data Types

Goal: translate data desriptions into the code.

In Algebraic Data Types, the model date with logical ORs and logical ANDs.
The two patterns are called product types (AND) and sum types (OR).

We need to struct the code following the structure of the data

// Product Type
type BType = {} 
type CType = {} 

type AType = {
    b: BType,
    c: CType
// Sum Type
type Type1 = {} 
type Type2 = {} 

type MType = {
    arge: Type1 | Type2

For Example

a website visitor is like as:

    - `OR`
        - Logged in as member
        - anonymous

Then we can give more detail for the logged in user:

    - `AND`
        - ID
        - email address

Then we can give more detail for the anonymous user:

    - `AND`
        - ID
type LoggedInUser = {
    ID: string
    email: string
type Anonymous = {
    ID: string

type Visitor = LoggedInUser | Anonymous
  1. Structure data with logical ANDs and ORs
  2. These are called algebraic data types
  3. Code follows immediately from structure of the data

Add a Comment