[英]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. 我正在尝试将函数应用于Matrix但我不知道如何继续。
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. 然后,一旦我的Matrix被定义,我想将我的函数
z95
应用于矩阵的每个元素。
Here's the signature of my z95
function (which allows to convert a integer into this integer modulo 95) 这是我的
z95
函数的签名(允许将整数转换为此整数模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. 我试图做一个双
map
也访问我的矩阵的元素,但后来我没有弄清楚如何应用我的z95
功能。
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. 您可以为类型定义
Functor
实例,这是将函数映射到容器元素的常用方法。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.