on 54e4e41 help sign in
Idris-dev/libs/base/Data/Complex.idr
71 lines 1.8 kB history raw
1{-
2 (c) 2012 Copyright Mekeor Melire
3-}
6module Data.Complex
8import Data.Floats
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
21instance Eq a => Eq (Complex a) where
22 (==) a b = realPart a == realPart b && imagPart a == imagPart b
24instance 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
31-- when we have a type class 'Fractional' (which contains Float and Double),
32-- we can do:
33{-
34instance Fractional a => Fractional (Complex a) where
35 (/) (a:+b) (c:+d) = let
36 real = (a*c+b*d)/(c*c+d*d)
37 imag = (b*c-a*d)/(c*c+d*d)
38 in
39 (real:+imag)
40-}
44------------------------------ Polarform
46mkPolar : Float -> Float -> Complex Float
47mkPolar radius angle = radius * cos angle :+ radius * sin angle
49cis : Float -> Complex Float
50cis angle = cos angle :+ sin angle
52magnitude : Complex Float -> Float
53magnitude (r:+i) = sqrt (r*r+i*i)
55phase : Complex Float -> Float
56phase (x:+y) = atan2 y x
59------------------------------ Conjugate
61conjugate : Num a => Complex a -> Complex a
62conjugate (r:+i) = (r :+ (0-i))
64-- We can't do "instance Num a => Num (Complex a)" because
65-- we need "abs" which needs "magnitude" which needs "sqrt" which needs Float
66instance Num (Complex Float) where
67 (+) (a:+b) (c:+d) = ((a+c):+(b+d))
68 (-) (a:+b) (c:+d) = ((a-c):+(b-d))
69 (*) (a:+b) (c:+d) = ((a*c-b*d):+(b*c+a*d))
70 fromInteger x = (fromInteger x:+0)
71 abs (a:+b) = (magnitude (a:+b):+0)