You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CIS194作业:Poly类型Num实例fromInteger函数类型不匹配求助

修复Poly类型的fromInteger实现错误

问题根源

报错的核心是类型不匹配:fromInteger要求返回Poly a类型,但你直接用P [n]构造出的是Poly Integer——因为输入的n是Integer类型,而a是实例声明中约束的任意Num类型(不一定是Integer)。

修复代码

只需要把Integer类型的n转换为a类型(借助Num类型类自带的fromInteger函数),再构造多项式即可:

instance Num a => Num (Poly a) where
    (+) = plus
    (*) = times
    negate = times (P [-fromInteger 1]) -- 顺便修正negate的类型问题
    fromInteger n = P [fromInteger n]
    abs    = undefined
    signum = undefined

为什么这样改

Num类型类提供了fromInteger :: Num b => Integer -> b函数,它的作用就是把Integer值转换为任意实现了Num的类型。这里我们用它把输入的n转成a类型,这样P [fromInteger n]的类型就变成了Poly a,完全符合实例声明的要求。

另外你的negate实现其实也有隐含的类型问题:原来的P [-1]是Poly Integer类型,但times需要的是Poly a参数。改成P [-fromInteger 1]后,就能生成正确的Poly a类型值,避免后续可能出现的类型错误。

内容的提问来源于stack exchange,提问作者cmal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:15:38