module Matrix where import Control.Applicative import Data.List (intercalate) newtype Mat a = Mat [[a]] type Pos = (Int, Int) instance Functor Mat where fmap f (Mat m) = Mat ((map . map) f m) instance (Show a) => Show (Mat a) where show (Mat m) = concatMap ((++"\n") . intercalate " " . map show) m -- | Safely access a list -- [4,1,5,9] ?? 2 == Just 5 -- [5,7] ?? 3 == Nothing (??) :: [a] -> Int -> Maybe a xs ?? n | n < 0 = Nothing [] ?? _ = Nothing (x:_) ?? 0 = Just x (_:xs) ?? n = xs ?? (n-1) -- | Split a list into sublists of length n -- group 2 [1..5] == [[1,2],[3,4],[5]] group _ [] = [] group n xs = take n xs : group n (drop n xs) -- | Create a matrix of indeces of a matrix indeces :: Mat a -> Mat Pos indeces (Mat m) = Mat (group y pos) where (x, y) = (length m, length (m !! 0)) pos = liftA2 (,) [0..x-1] [0..y-1] -- | Create a constant matrix constant :: a -> Int -> Int -> Mat a constant k x y = Mat (replicate x $ replicate y k)