From: Michael Orlitzky Date: Fri, 7 Dec 2018 14:54:28 +0000 (-0500) Subject: src/Normed.hs: combine zero- and nonzero-length implementations. X-Git-Url: http://gitweb.michael.orlitzky.com/?p=numerical-analysis.git;a=commitdiff_plain;h=40154d27bb940fc69f97870ef7ff7fb22ce97b87 src/Normed.hs: combine zero- and nonzero-length implementations. --- diff --git a/src/Normed.hs b/src/Normed.hs index 21c275f..28fbd28 100644 --- a/src/Normed.hs +++ b/src/Normed.hs @@ -8,7 +8,9 @@ where import BigFloat -import NumericPrelude hiding ( abs ) +-- Ensure that we don't use the Lattice.C "max" function, that +-- only works on Integer/Bool. +import NumericPrelude hiding ( abs, max ) import Algebra.Absolute ( abs ) import qualified Algebra.Absolute as Absolute ( C ) import qualified Algebra.Algebraic as Algebraic ( C ) @@ -16,13 +18,12 @@ import Algebra.Algebraic ( root ) import qualified Algebra.RealField as RealField ( C ) import qualified Algebra.ToInteger as ToInteger ( C ) import qualified Algebra.ToRational as ToRational ( C ) -import Data.Vector.Fixed ( S, Z ) import qualified Data.Vector.Fixed as V ( Arity, - map, - maximum ) + foldl, + map ) import Data.Vector.Fixed.Boxed ( Vec ) - +import qualified Prelude as P ( max ) import Linear.Vector ( element_sum ) @@ -59,22 +60,14 @@ instance Normed Double where norm_infty = abs . fromRational' . toRational --- | 'Normed' instance for vectors of length zero. These are easy. -instance Normed (Vec Z a) where - norm_p _ = const (fromInteger 0) - norm_infty = const (fromInteger 0) - - --- | 'Normed' instance for vectors of length greater than zero. We --- need to know that the length is non-zero in order to invoke --- V.maximum. We will generally be working with n-by-1 /matrices/ --- instead of vectors, but sometimes it's convenient to have these --- instances anyway. +-- | 'Normed' instance for vectors of any length. We will generally be +-- working with n-by-1 /matrices/ instead of vectors, but sometimes +-- it's convenient to have these instances anyway. -- -- Examples: -- -- >>> import Data.Vector.Fixed (mk3) --- >>> import Linear.Vector (Vec3) +-- >>> import Linear.Vector (Vec0, Vec3) -- >>> let b = mk3 1 2 3 :: Vec3 Double -- >>> norm_p 1 b :: Double -- 6.0 @@ -83,12 +76,16 @@ instance Normed (Vec Z a) where -- >>> norm_infty b :: Double -- 3.0 -- +-- >>> let b = undefined :: Vec0 Int +-- >>> norm b +-- 0.0 +-- instance (V.Arity n, Absolute.C a, ToRational.C a, Ord a) - => Normed (Vec (S n) a) where + => Normed (Vec n a) where norm_p p x = (root p') $ element_sum $ V.map element_function x where element_function y = fromRational' $ (toRational y)^p' p' = toInteger p - norm_infty x = fromRational' $ toRational $ V.maximum $ V.map abs x + norm_infty x = fromRational' $ toRational $ (V.foldl P.max 0) $ V.map abs x