我总结了一个矩阵列表,foldl1 (+)
因为我注意到它sum
实际上将左上角元素的总和作为 1x1 矩阵返回。
$ stack exec --resolver lts-12.5 --package matrix -- ghci
GHCi, version 8.4.3: http://www.haskell.org/ghc/ :? for help
Prelude> import Data.Matrix
Prelude Data.Matrix> t = [identity 2, identity 2] -- two 2x2 identity matrices
Prelude Data.Matrix> foldl1 (+) t
┌ ┐
│ 2 0 │
│ 0 2 │
└ ┘
Prelude Data.Matrix> sum t
┌ ┐
│ 2 │
└ ┘
这对我来说是出乎意料的,LYAH 建议sum = foldl1 (+)
¹ 甚至 hlint 建议我使用sum
而不是foldl1 (+)
as is 'removes error on []
'(附带问题:我如何优雅且[]
安全地总结矩阵?)
为什么是sum /= foldl1 (+)
矩阵,为什么通常不总是sum == foldl1 (+)
?
或者,排除空列表的情况:
为什么不是sum == foldl neutralElement (+)
?或具体sum == foldl (+) (zero 2 2)
在[identity 2, identity 2]
?
自己的工作:
Prelude Data.Matrix> :t sum
sum :: (Foldable t, Num a) => t a -> a
Prelude Data.Matrix> :info sum
class Foldable (t :: * -> *) where
...
sum :: Num a => t a -> a
...
-- Defined in ‘Data.Foldable’
来源sum
是:
sum :: Num a => t a -> a
sum = getSum #. foldMap Sum
的实例化Matrix
是:
instance Foldable Matrix where
foldMap f = foldMap f . mvect
instance Num a => Num (Matrix a) where
fromInteger = M 1 1 . V.singleton . fromInteger
negate = fmap negate
abs = fmap abs
signum = fmap signum
-- Addition of matrices.
{-# SPECIALIZE (+) :: Matrix Double -> Matrix Double -> Matrix Double #-}
{-# SPECIALIZE (+) :: Matrix Int -> Matrix Int -> Matrix Int #-}
(M n m v) + (M n' m' v')
-- Checking that sizes match...
| n /= n' || m /= m' = error $ "Addition of " ++ sizeStr n m ++ " and "
++ sizeStr n' m' ++ " matrices."
-- Otherwise, trivial zip.
| otherwise = M n m $ V.zipWith (+) v v'
-- Substraction of matrices.
...
-- Multiplication of matrices.
...
¹ 在添加整数的情况下