Skip to content

Instantly share code, notes, and snippets.

@stasimus
Created June 10, 2012 21:31
Show Gist options
  • Save stasimus/2907414 to your computer and use it in GitHub Desktop.
Save stasimus/2907414 to your computer and use it in GitHub Desktop.
case class Weapon(name: String, ammo: Long)
case class Soldier(rank: Int, weapon: Weapon)
case class Lens[R, F](get: R => F, set: (R, F) => R) {
def compose[Q](g: Lens[Q, R]): Lens[Q, F] =
Lens(get = get compose g.get,
set = (q, f) => g set(q, set(g get q, f)))
}
val weaponL = Lens[Soldier, Weapon](
get = _.weapon,
set = (s, w) => s.copy(weapon = w)
)
val ammoL = Lens[Weapon, Long](
get = _.ammo,
set = (w, a) => w.copy(ammo = a)
)
val nameL = Lens[Weapon, String](
get = _.name,
set = (w, n) => w.copy(name = n)
)
val soldierAmmoL = ammoL compose weaponL
val soldierWeaponName = nameL compose weaponL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment