简体   繁体   English

Function 组合,带有类型默认值的类型注释

[英]Function composition with type annotation for type defaults

Let's say I have the following type:假设我有以下类型:

data ImageSize = ImageSize {height :: Int, width :: Int}

I now want to convert that to a JSON array (for legacy API surface reasons):我现在想将其转换为 JSON 数组(出于旧版 API 表面原因):

instance ToJSON ImageSize where
  toJSON ImageSize{..} = Array $ fromList $ Number <$> map (fromFloatDigits . fromIntegral) [height, width]

This fails to compile with:这无法编译:

 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]’

This problem is (trivially) resolved by:这个问题(微不足道)通过以下方式解决:

toJSON ImageSize{..} = Array $ fromList $ Number <$> map (fromFloatDigits) [(fromIntegral height) :: Double, (fromIntegral width)]

But that feels very verbose and ugly.但这感觉非常冗长和丑陋。 Is there a way to attach the typecast into the composition?有没有办法将类型转换附加到组合中? Something like (fromFloatDigits. :: Double. fromIntegral) , but actually functional?类似于(fromFloatDigits. :: Double. fromIntegral)的东西,但实际上是功能性的吗?

Just use fromIntegral directly, no need to add an extra intermediate type.直接使用fromIntegral即可,无需额外添加中间类型。

toJSON ImageSize{..} = Array $ fromList $ Number <$> map fromIntegral [height, width]

But even simpler is to use toJSON ...但更简单的是使用toJSON ...

toJSON ImageSize{..} = toJSON [height, width]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM