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:

Visitor
    - `OR`
        - Logged in as member
        - anonymous

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

LoggedInUser
    - `AND`
        - ID
        - email address

Then we can give more detail for the anonymous user:

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

type Visitor = LoggedInUser | Anonymous
Summary
  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

發佈留言必須填寫的電子郵件地址不會公開。