Functor
s 是一个很简单的东西,名字很复杂。简单地说,Functor
s 是容器,您可以通过函数将函数映射到其值fmap
。列表是最熟悉的Functor
,因为fmap
只是map
。其他Functor
包括Maybe
、IO
和Either a
。
在此代码段中,您将定义Matrix
为 a Functor
,因此您要告诉编译器这Matrix
是一个可以映射函数的容器。出于这个问题的目的,fmap
用于定义类型类中的几个函数Num
。很容易看出这是如何工作的(假设有一个fromList :: [[a]] -> Matrix a
函数):
> fmap id $ fromList [[1, 2], [3, 4]]
fromList [[1, 2], [3, 4]]
> fmap (+1) $ fromList [[1, 2], [3, 4]]
fromList [[2, 3], [4, 5]]
> fmap show $ fromList [[1, 2], [3, 4]]
fromList [["1", "2"], ["3", "4"]]
对于其他Functor
s:
> fmap (+1) [1, 2, 3]
[2, 3, 4]
> fmap (*10) (Just 1)
Just 10
> fmap (*10) Nothing
Nothing
至于为什么Data.Monoid
要在源中导入 for Data.Matrix
,完全是因为功能
-- | Display a matrix as a 'String' using the 'Show' instance of its elements.
prettyMatrix :: Show a => Matrix a -> String
prettyMatrix m@(M _ _ v) = unlines
[ "( " <> unwords (fmap (\j -> fill mx $ show $ m ! (i,j)) [1..ncols m]) <> " )" | i <- [1..nrows m] ]
where
mx = V.maximum $ fmap (V.maximum . fmap (length . show)) v
fill k str = replicate (k - length str) ' ' ++ str
在作者选择使用<>
而不是将++
字符串连接在一起的情况下,列表的一种相当普通的用法Monoid
。它与类型完全无关Matrix
。