[英]Function composition with type annotation for type defaults
假設我有以下類型:
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
即可,無需額外添加中間類型。
toJSON ImageSize{..} = Array $ fromList $ Number <$> map fromIntegral [height, width]
但更簡單的是使用toJSON
...
toJSON ImageSize{..} = toJSON [height, width]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.