on 385dcbf help sign in
Idris-dev/libs/base/Data/Complex.idr
85 lines 2.3 kB history raw
1{-
2 (c) 2012 Copyright Mekeor Melire
3-}
6module Data.Complex
8%access public export
10------------------------------ Rectangular form
12infix 6 :+
13data Complex a = (:+) a a
15realPart : Complex a -> a
16realPart (r:+i) = r
18imagPart : Complex a -> a
19imagPart (r:+i) = i
21implementation Eq a => Eq (Complex a) where
22 (==) a b = realPart a == realPart b && imagPart a == imagPart b
24implementation Show a => Show (Complex a) where
25 showPrec d (r :+ i) = showParens (d >= plus_i) $ showPrec plus_i r ++ " :+ " ++ showPrec plus_i i
26 where plus_i : Prec
27 plus_i = User 6
30-- when we have an interface 'Fractional' (which contains Double),
31-- we can do:
32{-
33implementation Fractional a => Fractional (Complex a) where
34 (/) (a:+b) (c:+d) = let
35 real = (a*c+b*d)/(c*c+d*d)
36 imag = (b*c-a*d)/(c*c+d*d)
37 in
38 (real:+imag)
39-}
43------------------------------ Polarform
45mkPolar : Double -> Double -> Complex Double
46mkPolar radius angle = radius * cos angle :+ radius * sin angle
48cis : Double -> Complex Double
49cis angle = cos angle :+ sin angle
51magnitude : Complex Double -> Double
52magnitude (r:+i) = sqrt (r*r+i*i)
54phase : Complex Double -> Double
55phase (x:+y) = atan2 y x
58------------------------------ Conjugate
60conjugate : Neg a => Complex a -> Complex a
61conjugate (r:+i) = (r :+ (0-i))
63implementation Functor Complex where
64 map f (r :+ i) = f r :+ f i
66-- We can do "implementation Neg a => Num (Complex a)" because
67-- we don't need "abs", only (-)
68implementation Neg a => Num (Complex a) where
69 (+) (a:+b) (c:+d) = ((a+c):+(b+d))
70 (*) (a:+b) (c:+d) = ((a*c-b*d):+(b*c+a*d))
71 fromInteger x = (fromInteger x:+0)
73-- We can't do "implementation Neg a => Neg (Complex a)" because
74-- we need "abs" which needs "magnitude" which needs "sqrt" which needs Double
75implementation Neg (Complex Double) where
76 negate = map negate
77 (-) (a:+b) (c:+d) = ((a-c):+(b-d))
78 abs (a:+b) = (magnitude (a:+b):+0)
80-- As soon as abs moves out of Neg (issue #3500), the following would become a
81-- valid instance:
83-- implementation Neg a => Neg (Complex a) where
84-- negate = map negate
85-- (-) (a:+b) (c:+d) = ((a-c):+(b-d))