From: Michael Orlitzky Date: Sat, 8 Feb 2014 00:24:14 +0000 (-0500) Subject: Make safe indexing slower but not dependent on the number of rows/columns. X-Git-Url: https://gitweb.michael.orlitzky.com/?a=commitdiff_plain;h=d889338fd30522f43643c77e33b941f076f597b5;p=numerical-analysis.git Make safe indexing slower but not dependent on the number of rows/columns. --- diff --git a/src/Linear/Matrix.hs b/src/Linear/Matrix.hs index a5fbb84..611545f 100644 --- a/src/Linear/Matrix.hs +++ b/src/Linear/Matrix.hs @@ -38,7 +38,6 @@ import qualified Data.Vector.Fixed as V ( fromList, head, ifoldl, - length, map, maximum, replicate, @@ -145,23 +144,54 @@ instance (Show a) => Show (Mat m n a) where toList :: Mat m n a -> [[a]] toList (Mat rows) = map V.toList (V.toList rows) + -- | Create a matrix from a nested list. fromList :: (Arity m, Arity n) => [[a]] -> Mat m n a fromList vs = Mat (V.fromList $ map V.fromList vs) --- | Unsafe indexing. +-- | Unsafe indexing. Much faster than the safe indexing. (!!!) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> a (!!!) (Mat rows) (i, j) = (rows ! i) ! j -- | Safe indexing. +-- +-- Examples: +-- +-- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int +-- >>> m !!? (-1,-1) +-- Nothing +-- >>> m !!? (-1,0) +-- Nothing +-- >>> m !!? (-1,1) +-- Nothing +-- >>> m !!? (0,-1) +-- Nothing +-- >>> m !!? (0,0) +-- Just 1 +-- >>> m !!? (0,1) +-- Just 2 +-- >>> m !!? (1,-1) +-- Nothing +-- >>> m !!? (1,0) +-- Just 3 +-- >>> m !!? (1,1) +-- Just 4 +-- >>> m !!? (2,-1) +-- Nothing +-- >>> m !!? (2,0) +-- Nothing +-- >>> m !!? (2,1) +-- Nothing +-- >>> m !!? (2,2) +-- Nothing +-- (!!?) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> Maybe a -(!!?) matrix (i, j) - | i < 0 || j < 0 = Nothing - | i > (nrows matrix) - 1 = Nothing - | j > (ncols matrix) - 1 = Nothing - | otherwise = Just $ matrix !!! (i,j) +(!!?) matrix idx = + ifoldl2 f Nothing matrix + where + f k l found cur = if (k,l) == idx then (Just cur) else found -- | The number of rows in the matrix. @@ -841,5 +871,3 @@ ifoldl2 f initial (Mat rows) = row_function :: b -> Int -> Vec n a -> b row_function rowinit idx r = V.ifoldl (g idx) rowinit r - -