Last active
August 29, 2015 14:07
-
-
Save aoiroaoino/baf76a27c74e4a859d55 to your computer and use it in GitHub Desktop.
Lens Sample in Scalaz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz._, Scalaz._ | |
case class Position(x: Int, y: Int) | |
case class Panel(position: Position, obj: String) | |
val px = Lens.lensu[Position, Int]( (pos, _x) => pos.copy(x = _x), _.x) | |
/* | |
val px = Lens.lensu[Position, Int] ( | |
(pos: Position, tmpX: Int) => pos.copy(x = tmpX), | |
(pos: Position) => pos.x | |
) | |
*/ | |
val py = Lens.lensu[Position, Int]( (pos, _y) => pos.copy(y = _y), _.y) | |
/* | |
val px = Lens.lensu[Position, Int] ( | |
(pos: Position, tmpY: Int) => pos.copy(y = tmpY), | |
(pos: Position) => pos.y | |
) | |
*/ | |
val fp = Lens.lensu[Panel, Position]( (panel, pos) => panel.copy(position = pos), _.position) | |
val fo = Lens.lensu[Panel, String]( (panel, o) => panel.copy(obj = o), _.obj) | |
// initial data | |
val zero = Position(0, 0) | |
val zeroPanel = Panel(zero, "@") | |
// --- Sample1 --- | |
scala> px.get(zero) | |
res7: Int = 0 | |
scala> py.set(zero, 100) | |
res9: Position = Position(0,100) | |
scala> py.mod(_ + 5, zero) | |
res11: Position = Position(0,5) | |
// --- Sample2 --- | |
scala> fp.get(zeroPanel) | |
res15: Position = Position(0,0) | |
scala> fo.get(zeroPanel) | |
res16: String = @ | |
// --- Sample3 --- | |
// same andThen | |
val fpx = fp >=> px | |
// same compose | |
val fpy = py <=< fp | |
scala> fpx.get(zeroPanel) | |
res18: Int = 0 | |
scala> fpy.set(zeroPanel, 99) | |
res19: Panel = Panel(Position(0,99),@) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment