diff --git a/haskell/06-complex/complex.hs b/haskell/06-complex/complex.hs index 6236379..dfb7b25 100644 --- a/haskell/06-complex/complex.hs +++ b/haskell/06-complex/complex.hs @@ -3,30 +3,49 @@ {-# HLINT ignore "Use void" #-} import Test.HUnit -data Complex a = TODO +data Complex a = Complex a a deriving (Eq) -instance (Show a, Num a, Eq a) => Show (Complex a) where - -- show :: (Show a, Num a, Eq a) => Complex a -> String - -- TODO +instance (Show a, Num a, Eq a, Ord a) => Show (Complex a) where + show (Complex re im) + | re == 0 && im == 0 = "0" + | re == 0 && im == 1 = "i" + | re == 0 && im == -1 = "-i" + | re == 0 = show im ++ "i" + | im == 0 = show re + | im == 1 = show re ++ "+i" + | im == -1 = show re ++ "-i" + | im > 0 = show re ++ "+" ++ show im ++ "i" + | otherwise = show re ++ show im ++ "i" -instance (Num a, Floating a) => Num (Complex a) where - -- (+) :: (Num a, Floating a) => Complex a -> Complex a -> Complex a - -- (*) :: (Num a, Floating a) => Complex a -> Complex a -> Complex a - -- TODO - -- abs (Complex re im) = TODO - -- signum (Complex re im) = TODO - -- fromInteger n = TODO - -- negate :: (Num a, Floating a) => Complex a -> Complex a - -- negate (Complex re im) = Complex (negate re) (negate im) +instance (Num a, Floating a, Eq a) => Num (Complex a) where + (Complex re1 im1) + (Complex re2 im2) = Complex (re1 + re2) (im1 + im2) + (Complex re1 im1) - (Complex re2 im2) = Complex (re1 - re2) (im1 - im2) + (Complex re1 im1) * (Complex re2 im2) = Complex (re1 * re2 - im1 * im2) (re1 * im2 + im1 * re2) -instance (Fractional a, Floating a) => Fractional (Complex a) where - -- fromRational r = TODO - -- recip (Complex re im) = TODO - - -- (Complex re1 im1) / (Complex re2 im2) = TODO + abs (Complex re im) = Complex (sqrt (re * re + im * im)) 0 + signum (Complex re im) + | re == 0 && im == 0 = Complex 0 0 + | otherwise = let mag = sqrt (re * re + im * im) in Complex (re / mag) (im / mag) --- conj :: Num a => Complex a -> Complex a --- TODO + fromInteger n = Complex (fromInteger n) 0 + negate (Complex re im) = Complex (negate re) (negate im) + +instance (Fractional a, Floating a, Eq a) => Fractional (Complex a) where + fromRational r = Complex (fromRational r) 0 + recip (Complex re im) = + let denom = re * re + im * im + in Complex (re / denom) (negate im / denom) + + (Complex re1 im1) / (Complex re2 im2) = + let denom = re2 * re2 + im2 * im2 + in Complex ((re1 * re2 + im1 * im2) / denom) ((im1 * re2 - re1 * im2) / denom) + +conj :: (Num a) => Complex a -> Complex a +conj (Complex re im) = Complex re (negate im) + +-- Imaginary unit +i :: (Num a) => Complex a +i = Complex 0 1 tests :: Test tests =