Skip to content

Instantly share code, notes, and snippets.

@majk-p
Created July 11, 2023 21:29
Show Gist options
  • Save majk-p/dfdcf08bdfc3986c3dcd94cc02fa4f52 to your computer and use it in GitHub Desktop.
Save majk-p/dfdcf08bdfc3986c3dcd94cc02fa4f52 to your computer and use it in GitHub Desktop.
Introduction to Optics
//> using scala "3.3.0"
//> using dep "dev.optics::monocle-core:3.2.0"
//> using dep "dev.optics::monocle-macro:3.2.0"
import monocle.syntax.all._
case class Product(id: String, name: String, price: Double)
case class Shelf(id: String, product: Product)
case class Display(id: String, kind: "Ambient" | "Chilled", shelves: List[Shelf] )
case class Alley(id: String, displays: List[Display])
case class Shop(alleys: List[Alley])
val water = Product("1", "Bottle of water", 6.99)
val milk = Product("2", "Milk 1l", 3.85)
val cheese = Product("3", "Cheese", 7.99)
val ham = Product("4", "Ham", 9.99)
val shop = Shop(
alleys = List(
Alley(
id = "1",
displays = List(
Display("1", "Ambient", List(Shelf("1", water), Shelf("2", milk))),
Display("2", "Chilled", List(Shelf("3", cheese), Shelf("4", ham)))
)
)
)
)
val discounted =
shop
.focus(_.alleys)
.each
.refocus(_.displays)
.each
.refocus(_.shelves)
.each
.refocus(_.product.price)
.modify(_ * 0.9)
println(discounted)
@kubukoz
Copy link

kubukoz commented Jul 16, 2023

fair nuff, although the example already uses union types 😅

@majk-p
Copy link
Author

majk-p commented Jul 16, 2023

That's also true! I planned to update the post with a clarification anyway 😁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment