【问题标题】:Function composition with type annotation for type defaults具有类型默认值的类型注释的函数组合
【发布时间】:2020-09-01 07:34:13
【问题描述】:

假设我有以下类型:

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) 之类的东西,但实际上可以使用吗?

【问题讨论】:

  • 现在不能检查,但是使用TypeApplications 可以解决这个问题吗?在您最初的尝试中使用fromIntegral @Int

标签: haskell types type-conversion type-constraints


【解决方案1】:

直接使用fromIntegral即可,无需额外添加中间类型。

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

但更简单的是使用toJSON...

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

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    相关资源
    最近更新 更多