I'm just learning about data and I'm trying to somewhat define complex numbers with it.
So far I have the following:
data Complex = Complex Int Int deriving(Eq)
instance Show Complex where
show Complex a = a -- Not working
instance Num Complex where
Complex a b + Complex c d = Complex (a+c) (b+d)
-- etc.
What I'm trying to do is to instance Show in order to make the program print a string like a complex number, such as: "a + bi"
I understand why the code I wrote errors, since a is of type Complex and the program expects a string, but I can't wrap my head around how I can separate both numbers and then add "i" to b, as well as put the operator inbetween.
Any ideas?
The line
show Complex a = a
defines a function show
with two arguments, the first one being Complex
and the second one being a
. This copes with the signature of show
in class Show
, where we only find one argument.
Since that argument must be a Complex
, you probably want something like
show (Complex a b) = show a ++ " + " ++ show b ++ "i"
Note how we use show
on a
and b
of type Int
to convert them to strings, and then concatenate a bunch of strings using ++
.
Also note that when b
is negative the output of the above is suboptimal. You might want to change the function accordingly.