[英]Apply a function to each element of a matrix
我正在嘗試將函數應用於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))
然后,一旦我的Matrix被定義,我想將我的函數z95
應用於矩陣的每個元素。
這是我的z95
函數的簽名(允許將整數轉換為此整數模95)
z95 n = Z95(n %% 95)
z95 18 = 18%95
我試圖做一個雙map
也訪問我的矩陣的元素,但后來我沒有弄清楚如何應用我的z95
功能。
謝謝你的幫助!
您可以為類型定義Functor
實例,這是將函數映射到容器元素的常用方法。
instance Functor Matrice where
fmap f (Mat xss) = Mat (map (map f) xss)
現在你可以寫了
>> let m = Mat [[1,2,3],[4,5,6]]
>> fmap (+3) m -- => Mat [[4,5,6],[7,8,9]]
或者在你的情況下
>> fmap z95 m
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.