我在使用镜头库访问Map数据类型时遇到一些问题。
data Card
= Ferme
| Boulangerie
data PlayerState = PlayerState {
_psCards :: Map Card Int,
} deriving (Show)
data GameState = GameState {
_gsPlayers :: [PlayerState]
} deriving (Show)
访问Map
时遇到问题
step :: (MonadState s m, HasGameState s, MonadIO m) => m ()
step = do
i <- use $ gsPlayers . ix 0 . psCards . ix Ferme
出现以下错误:
• Could not deduce (Monoid Int) arising from a use of ‘ix’
from the context: (MonadState s m, HasGameState s, MonadIO m)
bound by the type signature for:
step :: forall s (m :: * -> *).
(MonadState s m, HasGameState s, MonadIO m) =>
m ()
这是因为我在同一行中使用了带有不同参数的ix
吗?
发布于 2019-03-14 23:10:38
这是因为ix
是遍历,而use
需要的是镜头。不同的是,镜头总是只有一个目标。一次遍历可以有零个或多个。在检索值时需要镜头的组合器在遍历时会意外地尝试将多个值组合在一起作为Monoid
。(它特别来自Const
的Applicative
实例。)在您的情况下,该尝试不会进行类型检查,因为目标类型不存在这样的实例,因此您会收到该错误消息。
您可能希望使用preuse
组合器而不是use
,以解决可能不存在的值。
https://stackoverflow.com/questions/55165769
复制相似问题