我想计算给定点的复多项式的值,以哈斯克尔为单位。
多项式以((Int,Int),Int)
元素的列表给出,其中对(Int,Int)
代表商的实部和虚部单位,其余Int
表示度数。因此,复点 x
中多项式的值计算为 a_i*(x^t)
之和,其中 a_i
是第 i
商和 t
次。
这是我haskell
代码:
type Komp = (Int, Int)
(+%) :: Komp -> Komp -> Komp
(r1, i1) +% (r2, i2) = (r1+r2, i1+i2)
(*%) :: Komp -> Komp -> Komp
(r1, i1) *% (r2, i2) = (r1*r2 - i1*i2, r1*i2 + i1*r2)
(^%) :: Komp -> Int -> Komp
k ^% 1 = k
k ^% n = (k ^% (n-1)) *% k
vredKompPol :: [(Komp,Int)] -> Komp -> Komp
vredKompPol ((k,s):poli) t = k*%(t^%s) +% (vredKompPol poli t)
+%
,*%
和^%
只不过是在由类型Komp
表示的复数上定义的运算+
、*
和^
。
拥抱加载得很好,但执行:
Main> vredKompPol [((1,1),2),((1,1),0)] (0,0)
引发错误:
ERROR - Control Stack Overflow
为什么会发生这种情况或如何调试它。
我至少发现了两个错误。导致您的问题的一个是您的(^%)
基本情况太高,因此
> (1,1) ^% 0
*** Exception: stack overflow
通过将基本情况更改为
k ^% 0 = (1, 0)
第二个是你没有vredKompPol
的基本情况,你可以通过添加一个子句来修复,比如
vredKompPol [] _ = (0, 0)
通过这两个更改,我得到:
*Main> vredKompPol [((1,1),2),((1,1),0)] (0,0)
(1,1)
这对我来说是正确的。
问题是你对%^
的实现只为n >= 1
定义,但你试图将其与n = 0
一起使用,这永远不会达到基本情况(n = 1
)。
现在,拥抱已经退出开发阶段,所以我建议改用ghci。在 ghci 中,您可以调试类似的问题,如下所示:
[jakob:~]$ ghci foo.hs
GHCi, version 7.8.4: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main ( foo.hs, interpreted )
Ok, modules loaded: Main.
设置一个标志以在 Ctrl-c 上启用中断:
*Main> :set -fbreak-on-error
跟踪有问题的函数:
*Main> :trace vredKompPol [((1,1),2),((1,1),0)] (0,0)
片刻之后,按 Ctrl-c 停止执行。
^CStopped at <exception thrown>
_exception :: e = _
:history
显示执行历史记录。
[<exception thrown>] *Main> :history
-1 : *% (foo.hs:6:1-56)
-2 : ^% (foo.hs:10:15-31)
-3 : ^% (foo.hs:10:22-24)
-4 : ^% (foo.hs:(9,1)-(10,31))
-5 : ^% (foo.hs:10:16-25)
-6 : *% (foo.hs:6:1-56)
-7 : ^% (foo.hs:10:15-31)
-8 : ^% (foo.hs:10:22-24)
-9 : ^% (foo.hs:(9,1)-(10,31))
-10 : ^% (foo.hs:10:16-25)
-11 : *% (foo.hs:6:1-56)
-12 : ^% (foo.hs:10:15-31)
-13 : ^% (foo.hs:10:22-24)
-14 : ^% (foo.hs:(9,1)-(10,31))
-15 : ^% (foo.hs:10:16-25)
-16 : *% (foo.hs:6:1-56)
-17 : ^% (foo.hs:10:15-31)
-18 : ^% (foo.hs:10:22-24)
-19 : ^% (foo.hs:(9,1)-(10,31))
-20 : ^% (foo.hs:10:16-25)
...
使用 :back
向上移动执行历史记录,以便使用 :show bindings
检查参数:
[<exception thrown>] *Main> :back
Logged breakpoint at foo.hs:6:1-56
_result :: Komp
[-1: foo.hs:6:1-56] *Main> :show bindings
_exception :: e = _
_result :: Komp = _
这里没有什么有趣的(可能是因为它是按下 Ctrl-c 时正在执行的函数)。向上移动一步,然后重试:
[-1: foo.hs:6:1-56] *Main> :back
Logged breakpoint at foo.hs:10:15-31
_result :: Komp
k :: Komp
n :: Int
[-2: foo.hs:10:15-31] *Main> :show bindings
_exception :: e = _
n :: Int = -12390
k :: Komp = (0,0)
_result :: Komp = _
[-2: foo.hs:10:15-31] *Main>
因此,它正在第 10 行执行,n = -12390
.这表明非终止递归存在问题。