在Haskell中为ToJSON添加独立派生
我想写这个数据类型:在Haskell中为ToJSON添加独立派生,json,haskell,aeson,Json,Haskell,Aeson,我想写这个数据类型: data GameState = GameState { players :: [Player], lasers :: [(Float, Float, Float)], asteroids :: [Asteroid], score :: Int, width :: Int, height :: Int, keys :: S.Set Key, lastTimeAsteroidAdded :: Int, s
data GameState = GameState {
players :: [Player],
lasers :: [(Float, Float, Float)],
asteroids :: [Asteroid],
score :: Int,
width :: Int,
height :: Int,
keys :: S.Set Key,
lastTimeAsteroidAdded :: Int,
screen :: Int,
mouseclicks :: S.Set (Float, Float)
}
deriving (Show, Generic, ToJSON)
到JSON文件。因此,我需要让GameState从ToJSON派生,但现在它说我需要为Key创建一个独立的派生实例。但是我该怎么做呢
我得到的信息是:
No instance for (ToJSON Key)
arising from the 'deriving' clause of a data type declaration
Possible fix:
use a standalone 'deriving instance' declaration,
so you can specify the instance context yourself
• When deriving the instance for (ToJSON GameState)
你问题的解决办法很简单。由于您无权访问Key(它在Gloss中定义),并且Key不派生Generic,因此首先必须为Key派生Generic的实例:
派生实例通用密钥
这确实需要使用以下额外扩展:
{-#语言标准派生}
现在您有了Key的通用实例,可以定义ToJSON的实例:
实例TOJSON键
在数据键=…
中,您还添加了派生(ToJson)
。我还没有创建键,键来自库Graphics.Gloss.Interface.IO.game,然后您实现了一个实例到json键,其中…