ch 2

Domain Modeling Made Functional

F#

What is Domain model ? 🤔

In software engineering, a domain model is a conceptual model of the domain

How can we get domain model?

domain model

  • User Story
  • Event Storming

Type System

Why Type System?

A well designed functional program, on the other hand, will have a strong focus on data types rather than behavior.-- Scott Wlaschin

  • Code Readability
  • Prevent errors
  • Pattern Matching
  • Domain Modeling

Type abbreviations(alias)

  • Code Readability
type [typename] = [existingType]
type Name = String
type Fruit = Apple

Have a Question

type FirstName = string
type LastName = string

let name firstName lastName = firstName + " " + lastName
let firstName: FirstName = "Jia-Wei"
let lastName: LastName = "Lin"
name firstName lastName //ok
name lastName firstName //ok

Prevent errors

type FirstName = FirstName of string
type LastName = LastName of string

let firstName = FirstName "Jia-Wei"
let lastName = LastName "Lin"
let name (FirstName firstName) (LastName lastName) = firstName + " " + lastName

name firstName lastName // ok
name lastName firstName // error

Pattern Matching

type Fruit =
    | Apple
    | Banana
    | Papaya

let fruitList = [ Apple; Banana; Papaya ]

for fruit in fruitList do
    match fruit with
    | Apple -> printfn "Yes! I love apple."
    | Banana -> printfn "Yes! I love banana."
    | Papaya -> printfn "Yes! I love papaya."

type Fruit =
    | Apple of string
    | Banana of string
    | Papaya of string

let fruitList =
    [ Apple "red apple"
      Banana "yellow banana"
      Papaya "Papaya!" ]

for fruit in fruitList do
    match fruit with
    | Apple value -> printfn "Yes! I love %A." value
    | Banana value -> printfn "Yes! I love %A." value
    | Papaya value -> printfn "Yes! I love %A." value

Algebraic Data Type (ADT)

  • Product Type ➡️ AND
  • Sum Type ➡️ OR

Product Type

A & B & C

Record

type Person1 = {Frst:string; Last:string}

Tuple

type Card = Suit * Rank

Sum Type

A + B + C

Union

type Fruit = Apple | Banana | Papaya

We can build up every thing with ADT

type UserContact ={
  FirstName: String50
  MiddleInitial: String1 option
  LastName: String50
  contactMethod: EmailAddress | PhoneNumber
}

Recap

  • Domain model
    • shared mental model
  • F# Type System
  • ADT
    • Product type ➡️ And
    • Sum type ➡️ Or

References

https://www.youtube.com/watch?v=2JB1_e5wZmU https://fsharpforfunandprofit.com/posts/overview-of-types-in-fsharp/

return to Outline