]> gitweb.michael.orlitzky.com - numerical-analysis.git/blob - src/TwoTuple.hs
Rename "norm" to "norm_2" in the Vector class.
[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). Also require (as
3 -- opposed to the built-in ordered pairs) that the elements have
4 -- matching types.
5 --
6 module TwoTuple
7 where
8
9 import Vector
10
11
12 data TwoTuple a = TwoTuple a a
13 deriving (Eq)
14
15 instance (Show a) => Show (TwoTuple a) where
16 show (TwoTuple x y) = "(" ++ (show x) ++ ", " ++ (show y) ++ ")"
17
18 instance Functor TwoTuple where
19 f `fmap` (TwoTuple x1 y1) = TwoTuple (f x1) (f y1)
20
21 instance (RealFloat a) => Vector (TwoTuple a) where
22 -- The standard Euclidean 2-norm. We need RealFloat for the square
23 -- root.
24 norm_2 (TwoTuple x y) = fromRational $ toRational (sqrt(x^2 + y^2))
25
26 -- The infinity norm, i.e. the maximum entry.
27 norm_infty (TwoTuple x y) =
28 fromRational $ max absx absy
29 where
30 absx = abs (toRational x)
31 absy = abs (toRational y)
32
33 -- | It's not correct to use Num here, but I really don't want to have
34 -- to define my own addition and subtraction.
35 instance Num a => Num (TwoTuple a) where
36 -- Standard componentwise addition.
37 (TwoTuple x1 y1) + (TwoTuple x2 y2) =
38 TwoTuple (x1 + x2) (y1 + y2)
39
40 -- Standard componentwise subtraction.
41 (TwoTuple x1 y1) - (TwoTuple x2 y2) =
42 TwoTuple (x1 - x2) (y1 - y2)
43
44 -- Left undefined to prevent mistakes. One sane definition
45 -- would be componentwise multiplication.
46 (*) _ _ = error "multiplication of vectors is undefined"
47
48 abs _ = error "absolute value of vectors is undefined"
49
50 signum _ = error "signum of vectors is undefined"
51
52 fromInteger x = TwoTuple (fromInteger x) (fromInteger x)