【问题标题】:Why is this functor definition giving me an error?为什么这个函子定义给我一个错误?
【发布时间】:2018-05-14 05:04:31
【问题描述】:
data PPMImage a = PPMImage {width :: Integer,
                        height :: Integer,
                        magicNumber :: Integer,
                        maxColor :: Integer,
                        pixels :: [a]} deriving (Show)

instance Functor PPMImage where
    fmap f (PPMImage w h m c p) = f PPMImage w h m c (f p)

我想我了解函子的整个包装和展开方面 - 用户 MCH 提供的this link 帮助很大。

函数和列表已经是函子,但是我定义的这个PPMImage没有默认函子实例。我正在尝试定义一个仅应用于PPMImage 的(像素)数组的函数,但我不断收到此错误:

Couldn't match expected type ‘[b]’ with actual type ‘b’
  ‘b’ is a rigid type variable bound by
    the type signature for:
      fmap :: forall a b. (a -> b) -> PPMImage a -> PPMImage b
    at New.hs:13:5-8
• In the fifth argument of ‘PPMImage’, namely ‘(f p)’
  In the expression: PPMImage w h m c (f p)
  In an equation for ‘fmap’:
      fmap f (PPMImage w h m c p) = PPMImage w h m c (f p)
• Relevant bindings include
    f :: a -> b (bound at New.hs:13:10)
    fmap :: (a -> b) -> PPMImage a -> PPMImage b (bound at New.hs:13:5)

我不明白为什么会这样,这个函子不就是解开原来的PPMImage,然后应用函数f,然后重新包装成一个新的PPMImage吗?

【问题讨论】:

标签: haskell functional-programming


【解决方案1】:

如果您从PPImage 前面删除f 并将mapfmap 添加到f p,它应该可以工作。 p是一个列表,所以你不能直接申请f,它也必须是fmapped覆盖p的内容。

instance Functor PPMImage where
    fmap f (PPMImage w h m c p) = PPMImage w h m c (fmap f p)

【讨论】:

  • 你不需要map f p而不是f p吗?
  • 是的,可以是map f pfmap f p
  • 这不是定义了我要在 PPMImage 上使用的函数吗?删除 f 时它不会为我编译
  • @user202729 注意到。但是,我已经对您的回复投了赞成票
猜你喜欢
  • 1970-01-01
  • 2021-03-19
  • 2013-11-14
  • 2020-12-25
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
相关资源
最近更新 更多