]> gitweb.michael.orlitzky.com - numerical-analysis.git/blob - src/TwoTuple.hs
Add a custom Show instance for TwoTuple.
[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 (TwoTuple x1 y1) = fromRational $ toRational (sqrt(x1^2 + y1^2))
25
26 -- | It's not correct to use Num here, but I really don't want to have
27 -- to define my own addition and subtraction.
28 instance Num a => Num (TwoTuple a) where
29 -- Standard componentwise addition.
30 (TwoTuple x1 y1) + (TwoTuple x2 y2) =
31 TwoTuple (x1 + x2) (y1 + y2)
32
33 -- Standard componentwise subtraction.
34 (TwoTuple x1 y1) - (TwoTuple x2 y2) =
35 TwoTuple (x1 - x2) (y1 - y2)
36
37 -- Left undefined to prevent mistakes. One sane definition
38 -- would be componentwise multiplication.
39 (*) _ _ = error "multiplication of vectors is undefined"
40
41 abs _ = error "absolute value of vectors is undefined"
42
43 signum _ = error "signum of vectors is undefined"
44
45 fromInteger x = TwoTuple (fromInteger x) (fromInteger x)