From ff83c063ad5cdb1bf9476678a010aa0cfb782a8f Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Sun, 14 Oct 2012 14:04:31 -0400 Subject: [PATCH] Add a Vector class and make TwoTuple (and several base types) instances of it. --- src/TwoTuple.hs | 9 +++++++++ src/Vector.hs | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 src/Vector.hs diff --git a/src/TwoTuple.hs b/src/TwoTuple.hs index 8493114..daeb6e4 100644 --- a/src/TwoTuple.hs +++ b/src/TwoTuple.hs @@ -4,13 +4,22 @@ module TwoTuple where +import Vector + + data TwoTuple a = TwoTuple a a deriving (Eq, Show) instance Functor TwoTuple where f `fmap` (TwoTuple x1 y1) = TwoTuple (f x1) (f y1) +instance (RealFloat a) => Vector (TwoTuple a) where + -- The standard Euclidean 2-norm. We need RealFloat for the square + -- root. + norm (TwoTuple x1 y1) = fromRational $ toRational (sqrt(x1^2 + y1^2)) +-- | It's not correct to use Num here, but I really don't want to have +-- to define my own addition and subtraction. instance Num a => Num (TwoTuple a) where -- Standard componentwise addition. (TwoTuple x1 y1) + (TwoTuple x2 y2) = diff --git a/src/Vector.hs b/src/Vector.hs new file mode 100644 index 0000000..e608a50 --- /dev/null +++ b/src/Vector.hs @@ -0,0 +1,24 @@ +{-# LANGUAGE FlexibleInstances #-} + +-- | The 'Vector' class represents elements of a normed vector +-- space. We define instances for all common numeric types. +module Vector +where + +import Data.Number.BigFloat + +class Vector a where + norm :: RealFrac b => a -> b + +-- Define instances for common numeric types. +instance Vector Integer where + norm = fromInteger + +instance Vector Rational where + norm = fromRational + +instance Epsilon e => Vector (BigFloat e) where + norm = fromRational . toRational + +instance Vector Double where + norm = fromRational . toRational -- 2.43.2