我有以下代码。当给定游戏状态时,我希望能够修改活跃玩家的生命值。我想到了使用activePlayer
镜头,但是当我尝试将其与-=
运算符结合使用时,会收到以下错误:
> over (activePlayer.life) (+1) initialState
<interactive>:2:7:
No instance for (Contravariant Mutator)
arising from a use of `activePlayer'
Possible fix:
add an instance declaration for (Contravariant Mutator)
In the first argument of `(.)', namely `activePlayer'
In the first argument of `over', namely `(activePlayer . life)'
In the expression: over (activePlayer . life) (+ 1) initialState``
需要进行翻译的代码如下:
{-# LANGUAGE TemplateHaskell #-}
module Scratch where
import Control.Lens
import Control.Monad.Trans.Class
import Control.Monad.Trans.State
import Data.Sequence (Seq)
import qualified Data.Sequence as S
data Game = Game
{ _players :: (Int, Seq Player) -- active player, list of players
, _winners :: Seq Player
}
deriving (Show)
initialState = Game
{ _players = (0, S.fromList [player1, player2])
, _winners = S.empty
}
data Player = Player
{ _life :: Integer
}
deriving (Show, Eq)
player1 = Player
{ _life = 10
}
player2 = Player
{ _life = 10
}
makeLenses ''Game
makeLenses ''Player
activePlayer
:: (Functor f, Contravariant f) =>
(Player -> f Player) -> Game -> f Game
activePlayer = players.to (\(i, ps) -> S.index ps i)
每位玩家按顺序轮流行动。我需要同时跟踪所有玩家以及当前处于活跃状态的玩家,这就是我构建结构的原因,尽管我也可以采用不同的结构,因为我可能还没有找到正确的结构。
activePlayer
的定义允许它作为 getter,但不允许它作为 setter。你已经告诉它如何从 Sequence 中获取一个 player,但没有告诉它如何更改 active player,因此它不能用于修改 players。请查看to
的类型 ---> :i to
的结果是to :: (a -> c) -> Getter a b c d
。 - Chris Taylor