假设我具有以下类型:
data ImageSize = ImageSize {height :: Int, width :: Int}
我现在想将其转换为JSON数组(出于遗留API表面原因):
instance ToJSON ImageSize where
toJSON ImageSize{..} = Array $ fromList $ Number <$> map (fromFloatDigits . fromIntegral) [height, width]
无法编译为:
error: [-Wtype-defaults, -Werror=type-defaults]
• Defaulting the following constraints to type ‘Double’
(RealFloat a0)
arising from a use of ‘fromFloatDigits’
at lib/Filler/Filler/Filler/Filler/Filler/ImageSize.hs:14:63-77
(Num a0)
arising from a use of ‘fromIntegral’
at lib/Filler/Filler/Filler/Filler/Filler/ImageSize.hs:14:80-98
• In the first argument of ‘map’, namely ‘fromFloatDigits’
In the second argument of ‘(<$>)’, namely
‘map (fromFloatDigits . fromIntegral) [height, width]’
In the second argument of ‘($)’, namely
‘Number
<$> map (fromFloatDigits . fromIntegral) [height, width]’
此问题已(通过以下方式解决):
toJSON ImageSize{..} = Array $ fromList $ Number <$> map (fromFloatDigits) [(fromIntegral height) :: Double, (fromIntegral width)]
但是感觉很冗长和丑陋。有没有办法将类型转换附加到合成中? (fromFloatDigits . :: Double . fromIntegral)
之类的东西,但实际上起作用吗?
直接使用fromIntegral
,无需添加额外的中间类型。