Skip to content

Instantly share code, notes, and snippets.

@quephird
Created March 29, 2015 03:50
Show Gist options
  • Select an option

  • Save quephird/2579ddfc242b5c95e05d to your computer and use it in GitHub Desktop.

Select an option

Save quephird/2579ddfc242b5c95e05d to your computer and use it in GitHub Desktop.
Just a dopey implementation of a Complex type in PureScript
module Data.Complex where
data Complex = Complex Number Number
instance showComplex :: Show Complex where
show (Complex x y) = show x ++ " + " ++ show y ++ "i"
instance eqComplex :: Eq Complex where
(==) (Complex x y) (Complex x' y') = (x == x') && (y == y')
(/=) (Complex x y) (Complex x' y') = (x /= x') || (y /= y')
complexAdd :: Complex -> Complex -> Complex
complexAdd (Complex x y) (Complex x' y') = Complex (x + x') (y + y')
complexMultiply :: Complex -> Complex -> Complex
complexMultiply (Complex x y) (Complex x' y') = Complex (x * x' - y * y') (x * y' + x' * y)
instance semiringComplex :: Semiring Complex where
(+) = complexAdd
(*) = complexMultiply
zero = Complex 0 0
one = Complex 1 0
complexSubtract :: Complex -> Complex -> Complex
complexSubtract (Complex x y) (Complex x' y') = Complex (x - x') (y - y')
instance ringComplex :: Ring Complex where
(-) = complexSubtract
complexDivide :: Complex -> Complex -> Complex
complexDivide (Complex x y) (Complex x' y') = Complex x'' y'' where
x'' = (x * x' - y * y') / (x' * x' + y' * y')
y'' = (x' * y - x * y') / (x' * x' + y' * y')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment