-2

我是 Haskell 的新手。
我不知道为什么我们instance Functor Matrix在下面的代码中使用幺半群以及如何instance Functor Matrix工作?

instance Functor Matrix where
    fmap f (M n m v) = M n m $ fmap (fmap f) v

instance Num a => Num (Matrix a) where
    fromInteger = M 1 1 . V.singleton . V.singleton . fromInteger
    negate = fmap negate
    (+) = add
    (*) = mult
    abs = fmap abs
    signum = fmap signum

scalarMult :: Num a => a -> Matrix a -> Matrix a
    scalarMult = fmap . (*)

我知道函子对于negate, (*), abs,是必需的signum,但我需要详细解释。请帮帮我。

4

1 回答 1

3

Functors 是一个很简单的东西,名字很复杂。简单地说,Functors 是容器,您可以通过函数将函数映射到其值fmap。列表是最熟悉的Functor,因为fmap只是map。其他Functor包括MaybeIOEither 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"]]

对于其他Functors:

> 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

于 2014-05-28T14:25:13.160 回答