]> gitweb.michael.orlitzky.com - numerical-analysis.git/blob - src/TwoTuple.hs
Add a Vector class and make TwoTuple (and several base types) instances of it.
[numerical-analysis.git] / src / TwoTuple.hs
1 -- | Implement ordered pairs all over again for fun (and to make sure
2 -- that we can manipulate them algebraically).
3 --
4 module TwoTuple
5 where
6
7 import Vector
8
9
10 data TwoTuple a = TwoTuple a a
11 deriving (Eq, Show)
12
13 instance Functor TwoTuple where
14 f `fmap` (TwoTuple x1 y1) = TwoTuple (f x1) (f y1)
15
16 instance (RealFloat a) => Vector (TwoTuple a) where
17 -- The standard Euclidean 2-norm. We need RealFloat for the square
18 -- root.
19 norm (TwoTuple x1 y1) = fromRational $ toRational (sqrt(x1^2 + y1^2))
20
21 -- | It's not correct to use Num here, but I really don't want to have
22 -- to define my own addition and subtraction.
23 instance Num a => Num (TwoTuple a) where
24 -- Standard componentwise addition.
25 (TwoTuple x1 y1) + (TwoTuple x2 y2) =
26 TwoTuple (x1 + x2) (y1 + y2)
27
28 -- Standard componentwise subtraction.
29 (TwoTuple x1 y1) - (TwoTuple x2 y2) =
30 TwoTuple (x1 - x2) (y1 - y2)
31
32 -- Left undefined to prevent mistakes. One sane definition
33 -- would be componentwise multiplication.
34 (*) _ _ = error "multiplication of vectors is undefined"
35
36 abs _ = error "absolute value of vectors is undefined"
37
38 signum _ = error "signum of vectors is undefined"
39
40 fromInteger x = TwoTuple (fromInteger x) (fromInteger x)