life/Matrix.hs
2014-12-19 20:23:45 +01:00

29 lines
812 B
Haskell

module Matrix where
import Data.List (intercalate)
data 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)
-- | Create a matrix of indeces of a matrix
indeces :: Mat a -> Mat Pos
indeces (Mat m) = Mat [[(x,y) | y <- [0..length (m !! x)-1]] |
x <- [0..length m-1]]
-- | Create a matrix of zeros
zeros :: Int -> Int -> Mat Int
zeros x y = Mat (replicate x $ replicate y 0)