首页 > 解决方案 > 为什么这个函子定义给我一个错误?

问题描述

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 提供的这个链接有很大帮助。

函数和列表已经是函子,但PPMImage我定义的这个没有默认函子实例。我正在尝试定义一个将仅应用于 a 的(像素)数组的,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吗?

标签: haskellfunctional-programming

解决方案


如果您f从前面删除 fromPPImage并添加mapor fmapto ,它应该可以工作f pp是一个列表,所以你不能f直接申请,它还必须fmap覆盖p.

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

推荐阅读