i've created a data type for complex numbers, and i am trying to create an instance of Num for this datatype. I have been trying to add the negate line in because it is necessary for my show function, however I keep getting this error - "negate" is not a data constructor.
Here is the code for the instance:
instance Num Complex where
(C u v) + (C x y) = (C (u+x) (v+y))
(C u v) * (C x y) = (C (u*x) (-v*y)) + (C (v*x) (u*y))
(C u v) - (C x y) = (C (u+(-x)) (v+(-y)))
negate
abs (C x y) = C (root (x*x + y*y)) 0
signum (C x y) = if (x==0 && y==0) then 0 else 1
fromInteger n = C (fromInteger n) 0
Any help filling in the negate line would be greatly appreciated.
negate :: Num a => a -> a
returns the 'negative' value of its argument. How do you negate a complex number? In other words, if you havex+iy
, what values ofu
andv
do you need to havex+iy + u+iv = 0
? – user824425u-x
instead ofu+(-x)
? Multiplication could also be written a bit more compactly. —I have been trying to add the negate line in because it is necessary for my show function
– I don't know what you mean by that, but it sounds like you've got something wrong. What has this to do with a show function? –signum
(which admittedly isn't normally defined for complex numbers at all) should, like all the other functions, certainly be equivalent to its real version when constricted to reals, i.e.signum (-π)
should be-1
, not 1. – leftaroundaboutshow (C a (-b)) = "(" ++ show a ++ " - " ++ show b ++ "i)"
The reason for this stuff is to eventually solve polynomials with complex numbers. – edept(-b)
isn't a pattern, so that can't work. You'll need something likeshow (C a b) | b < 0 = "(" ++ show a ++ " - " ++ show (-b) ++ "i)" | b == 0 = show a | otherwise = "(" ++ show a ++ " + " ++ show b ++ "i)"
– Daniel Fischer