Skip to content

Instantly share code, notes, and snippets.

@MadaraUchiha
Created May 25, 2020 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MadaraUchiha/14f329790c5e29ef054c720efc061488 to your computer and use it in GitHub Desktop.
Save MadaraUchiha/14f329790c5e29ef054c720efc061488 to your computer and use it in GitHub Desktop.
type CartItem = string // placeholder for a more complicated type
type EmptyState = NoItems // don't use empty list! We want to
// force clients to handle this as a
// separate case. E.g. "you have no
// items in your cart"
type ActiveState = { UnpaidItems : CartItem list; }
type PaidForState = { PaidItems : CartItem list;
Payment : decimal}
type Cart =
| Empty of EmptyState
| Active of ActiveState
| PaidFor of PaidForState
type CartItem = string // placeholder for a more complicated type
type EmptyState = NoItems // don't use empty list! We want to
// force clients to handle this as a
// separate case. E.g. "you have no
// items in your cart"
type ActiveState = { UnpaidItems : CartItem list; }
type PaidForState = { PaidItems : CartItem list;
Payment : decimal}
type Cart =
| Empty of EmptyState
| Active of ActiveState
| PaidFor of PaidForState
type EmptyState with
member this.Add = addToEmptyState
type ActiveState with
member this.Add = addToActiveState this
member this.Remove = removeFromActiveState this
member this.Pay = payForActiveState this
let addItemToCart cart item =
match cart with
| Empty state -> state.Add item
| Active state -> state.Add item
| PaidFor state ->
printfn "ERROR: The cart is paid for"
cart
let removeItemFromCart cart item =
match cart with
| Empty state ->
printfn "ERROR: The cart is empty"
cart // return the cart
| Active state ->
state.Remove item
| PaidFor state ->
printfn "ERROR: The cart is paid for"
cart // return the cart
let displayCart cart =
match cart with
| Empty state ->
printfn "The cart is empty" // can't do state.Items
| Active state ->
printfn "The cart contains %A unpaid items"
state.UnpaidItems
| PaidFor state ->
printfn "The cart contains %A paid items. Amount paid: %f"
state.PaidItems state.Payment
type Cart with
static member NewCart = Cart.Empty NoItems
member this.Add = addItemToCart this
member this.Remove = removeItemFromCart this
member this.Display = displayCart this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment