Equinox
Equinox

Reputation: 137

Apply a function to each element of a matrix

I'm trying to apply a function to a Matrix but I don't know how to proceed.

Here's how I define my Matrix :

data Matrice a = Mat [[a]]

montre [] = "/"
montre (t:q) = "" ++ (Pp.printf "%5s" (show t)) ++ " " ++ (montre q)

instance (Show a) => Show (Matrice a) where
        show (Mat ([])) = ""
        show (Mat (t:q)) = "/" ++ (montre t) ++ "\n" ++ (show (Mat q))

Then, once my Matrix is defined I'd like to apply my function z95 to each of the elements of the matrix.

Here's the signature of my z95 function (which allows to convert a integer into this integer modulo 95)

z95 n = Z95(n %% 95)
z95 18 = 18%95

I tried to do a double map too access the elements of my Matrix but then I didn't figure out how to apply my z95 function.

Thanks fo the help!

Upvotes: 4

Views: 1355

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 47402

You could define a Functor instance for your type, which is the usual way to map a function over the elements of a container.

instance Functor Matrice where
  fmap f (Mat xss) = Mat (map (map f) xss)

Now you can write

>> let m = Mat [[1,2,3],[4,5,6]]
>> fmap (+3) m -- => Mat [[4,5,6],[7,8,9]]

or in your case

>> fmap z95 m

Upvotes: 7

Related Questions