简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM