gpt4 book ai didi

haskell - 定义函数的未定义错误

转载 作者:行者123 更新时间:2023-12-04 17:18:37 25 4
gpt4 key购买 nike

我正在尝试实现一个乘以多项式的函数(使用列表表示 -- 3x^2 + 5x + 2 = P [2,5,3]):

newtype Poly a = P [a]

plus :: Num a => Poly a -> Poly a -> Poly a
plus (P a) (P b) = P (map (\(y,z) -> z + y) (zipWithPadding 0 a b))
where
zipWithPadding :: (Num a) => a -> [a] -> [a] -> [(a, a)]
zipWithPadding e (aa: as) (bb: bs) = ((aa, bb): zipWithPadding e as bs)
zipWithPadding e [] bs = zip (repeat e) bs
zipWithPadding e as [] = zip as (repeat e)

times :: Num a => Poly a -> Poly a -> Poly a
times (P a) (P b) = sum $ multList 0 [] a b
where
multList :: Num a => Int -> [Poly a] -> [a] -> [a] -> [Poly a]
multList _ s [] _ = s
multList e s (aa:as) bs = multList (e + 1) (s ++ (multElement e aa bs)) as bs

multElement :: Num a => Int -> a -> [a] -> [Poly a]
multElement e aa bs = [P $ replicate e 0 ++ (map (*aa) bs)]


instance Num a => Num (Poly a) where
(+) = plus
(*) = times
negate = undefined
fromInteger = undefined
-- No meaningful definitions exist
abs = undefined
signum = undefined

但是,当我尝试运行时,出现了一个undefined 错误:

*HW04> times (P [1,2,2]) (P [1,2])
*** Exception: Prelude.undefined

我很困惑。

最佳答案

很明显,您正在调用 Poly 的 Num 实例中的 undefined 方法之一。

您可以使用这些定义来确定调用的是哪个:

negate      = error "Poly negate undefined"
fromInteger = error "Poly fromInteger undefined"
abs = error "Poly abs undefined"
signum = error "Poly signum undefined"

运行测试表达式产生:

Poly *** Exception: Poly fromInteger undefined

问题出在您对 sum 的使用上,它本质上定义为:

sum xs = foldl (+) 0 xs

因此调用 fromInteger 0。您可以通过以下方式解决此问题:

fromInteger x = P [ fromInteger x ]

更新

Poly afromInteger 需要这样定义的原因是因为我们需要构造一个 Num a 值列表,以及 fromInteger x是从整数值 x 创建 Num a 的方法。

关于haskell - 定义函数的未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39080419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com