Structural Recursion

Goal: Tramsform and implete algebraic data types

structure of the code follows structure of the data
We have two patterns need to follow:

  1. pattern matching
  2. polymorphism

In the First, we defined a algebraic data type

type ADType = {
    type: string
}
type Email = ADType & {
    host: string
    address: string
} 

type Address = ADType & {
    country: string
    address: string
} 

type ConnectMethod = Email | Address
const aUser_ConnectMethod: ConnectMethod = {
    type: "email",
    host: "host",
    address: "add"
}

const bUser_ConnectMethod: ConnectMethod = {
    type: "address",
    country: "country",
    address: "address"
}
pattern matching
const SendNotificationToUser = (method: ConnectMethod) => {
    switch(method.type){
        case "email":{
            console.log("the user chiose email method to notify")
            break;
        }
        case "address":{
            console.log("the user chiose address method to notify")
            break;
        }
    }
}

SendNotificationToUser(aUser_ConnectMethod)
>>> the user chiose email method to notify
polymorphism
interface NotifyMethod {
    (method: ConnectMethod): void;
}
const SendEMail: NotifyMethod = (m: Email): void => {
    console.log(`the user chiose email method to notification`)
}
const SendMail: NotifyMethod = (m: Address): void =>{
    console.log(`the user chiose address method to notification`)
}
SendEMail(aUser_ConnectMethod)
SendMail(bUser_ConnectMethod)
>>> the user chiose email method to notification
>>> the user chiose address method to notification
Summary
  • Processing algebraic data types immediately follows from the structure of the data
  • choose between pattern matching and polymorphism by your perferred

Add a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *