Haskell中实现函子fmap时出现类型匹配错误求助
自定义WarningAccumulator的Functor实例类型错误解决
问题重现
你定义的自定义数据类型:
newtype WarningAccumulator w a = WarningAccumulator (a,[w]) deriving (Show,Eq)
实现fmap时的代码:
instance Functor (WarningAccumulator w) where fmap :: (a -> b) -> WarningAccumulator w a -> WarningAccumulator w b fmap f (WarningAccumulator (list, value)) = WarningAccumulator(list, f value)
收到的报错信息:
Couldn't match type ‘a’ with ‘b’ Expected: WarningAccumulator w b Actual: WarningAccumulator w a
错误原因
核心问题是模式匹配的参数顺序和数据类型定义完全颠倒:
你定义WarningAccumulator时,构造器参数是(a,[w])——第一个元素是a类型的业务值,第二个是[w]类型的警告列表。但你在fmap的模式匹配里写了(list, value),错误地把第一个元素当成了警告列表(对应[w]),第二个当成了业务值(对应a)。
这导致f value中,value的实际类型是[w],和f要求的a->b类型不匹配。最终返回的WarningAccumulator(list, f value)仍属于WarningAccumulator w a类型,和预期的WarningAccumulator w b冲突,触发类型不匹配错误。
修复方案
修正模式匹配的参数顺序,和数据类型定义保持一致,同时调整fmap的逻辑:
instance Functor (WarningAccumulator w) where fmap :: (a -> b) -> WarningAccumulator w a -> WarningAccumulator w b fmap f (WarningAccumulator (value, warnings)) = WarningAccumulator(f value, warnings)
此时f作用在正确的a类型值上,返回b类型,最终构造出符合要求的WarningAccumulator w b类型结果。
内容的提问来源于stack exchange,提问作者chen
相关产品推荐
相关产品推荐

