How to determine which lens to install

I have a type of record in my Haskell code in which I want to define a lens that can be used as a getter and as a setter. The code is as follows:

data Players = Players { _white :: Player
                       , _black :: Player
                       } deriving (Show, Eq)
makeLenses ''Players
_byColor :: Color -> Players -> Player
_byColor White = _white
_byColor Black = _black
byColor col = to (_byColor col)

Players- This is a record with a white and black player. I want to be able to get the player by color in the lens. For instance.

players ^. byColor White . hp  -- Access health-points of player

However, I also want to set the property of the player selected in color. For instance. within a monad state with a Gamefield record _players.

let current = White
players . byColor current . hp %= (-1)

With my current definition, byColorhowever, the code cannot compile with the following error message:

No instance for (Contravariant Identity)
  arising from a use of `byColor'
Possible fix:
  add an instance declaration for (Contravariant Identity)

What am I doing wrong?

+4
source share
1 answer

to , . , , :

byColor :: Color -> Lens' Players Player
byColor White = white
byColor Black = black
+3

Source: https://habr.com/ru/post/1568768/


All Articles