0
votes

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.

1
negate :: Num a => a -> a returns the 'negative' value of its argument. How do you negate a complex number? In other words, if you have x+iy, what values of u and v do you need to have x+iy + u+iv = 0?user824425
A couple of notes: Why not just u-x instead of u+(-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.leftaroundabout
@leftaroundabout I will tidy those bits up, it's just the way i wrote it initially. I have written a show function to output the complex numbers in a better way. E.g. the line I am trying to get to work is show (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 like show (C a b) | b < 0 = "(" ++ show a ++ " - " ++ show (-b) ++ "i)" | b == 0 = show a | otherwise = "(" ++ show a ++ " + " ++ show b ++ "i)"Daniel Fischer
@DanielFischer Thanks for the help, this resolved the issue.edept

1 Answers

4
votes

I presume you are doing this as a learning exercise, otherwise you would simply use Data.Complex, right?

So instead of just giving you the answer, I shall answer your question by asking you another question.

negate {-something-} = {-something-}

Can you fill in anything of the two "something"s? If you can't fill one of them in completely, fair enough, but make it clean that you know where the remaining gaps to be filled in are.

Btw, your definition of signum is wrong. (You should have abs z * signum z = z for all z.)