我有以下代碼。我希望能夠在給定遊戲狀態時修改主動玩家的生活。我想出了一個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' –