Let’s play a game. There are two piles we’re going to use, both consisting of black/white sided chips.
data Pile = Pile { _blacks, _whites :: Int }
makeLenses ''Pile
data Game = Game { _pileA, _pileB :: Pile }
makeLenses ''Game
A really clever move would be to turn over a black chip in pile A, and a white chip — in pile B. But how?
cleverMove :: Game -> Game
cleverMove game = game & pileA . blacks -~ 1
& pileA . whites +~ 1
& pileB . blacks +~ 1
& pileB . whites -~ 1
Not very elegant. How can I do it without referencing each pile twice?
The only thing I came up with (and I don’t like it):
cleverMove game = game & pileA %~ (blacks -~ 1)
. (whites +~ 1)
& pileB %~ (blacks +~ 1)
. (whites -~ 1)
(Sorry in advance if it’s obvious — I’m kinda new to lenses and I feel lost in the sea of combinators and operators lens
offers. There’s probably everything for everybody’s needs hiding there. Not that it’s bad, of course! but I wish there was also a complete manual included.)
do
blocks and further levels of nesting. – Beachheadlet
orwhere
block, and start naming things. – Bow