haskell - 为什么这个函子定义给我一个错误?
问题描述
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
吗?
解决方案
如果您f
从前面删除 fromPPImage
并添加map
or fmap
to ,它应该可以工作f p
。p
是一个列表,所以你不能f
直接申请,它还必须fmap
覆盖p
.
instance Functor PPMImage where
fmap f (PPMImage w h m c p) = PPMImage w h m c (fmap f p)
推荐阅读
- android - 他从哪里拿的号码?自定义数字键盘 (Android Kotlin)
- reactjs - TS1128:需要声明或声明(文件结尾)
- javascript - twitter api - nodejs问题
- ios - 作为 UIView 的子视图的程序化 UIButton 没有响应
- json - 无法在 JSON 邮递员中提取出勤数据
- java - 为什么这个 JPanel 在第一次查看后会删除所有项目?
- twilio - 无法在 Twilio Flex 中接收媒体附件文件
- c# - 如何用C#删除文件的最后一个字符
- java - 如何使用 Java 从文件中读取一系列平面缓冲区
- latex - 如何在多列环境中放置和对齐图形