我有以下代码。我希望能够在给定游戏状态时修改主动玩家的生活。我想出了一个activePlayer
镜头,但当我尝试,结合了-=
操作我收到以下错误使用它:Haskell - 透镜,使用'to'功能
> 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 - 你已经告诉它如何将一名玩家拉出序列,但不知道如何改变主动玩家 - 因此它不能用来修改玩家。查看'''''''的类型:我将'输出到'::(a - > c) - > Getter a b c d' –