I want to compute value of a complex polynomial at the given point, in haskell.
Polynomial is given as a list of ((Int,Int),Int)
elements, where the pair (Int,Int)
stands for real and imaginary unit of the quotient, and the remaining Int
represents degree. Therefore, value of the polynomial in complex point x
is computed as the sum of a_i*(x^t)
where a_i
is the i
th quotient and t
degree.
Here is my haskell
code:
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)
+%
, *%
and ^%
are nothing more but operations +
, *
and ^
defined over complex numbers represented by the type Komp
.
It loads fine with hugs, but execution:
Main> vredKompPol [((1,1),2),((1,1),0)] (0,0)
throws an error:
ERROR - Control Stack Overflow
which I don't know why it happens or how to debug it.
There are at least two bugs I spot. The one causing your problem is that your base case for (^%)
is too high, so
> (1,1) ^% 0
*** Exception: stack overflow
Fix it by changing the base case to
k ^% 0 = (1, 0)
The second is that you have no base case for vredKompPol
, which you can fix by adding a clause like
vredKompPol [] _ = (0, 0)
With these two changes, I get:
*Main> vredKompPol [((1,1),2),((1,1),0)] (0,0)
(1,1)
That looks right to me.