首页 > 解决方案 > 为什么 sum == foldl1 (+) 不是?

问题描述

我总结了一个矩阵列表,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.
 ...

¹ 在添加整数的情况下

标签: haskellmatrixsumfoldfoldable

解决方案


因为Data.Matrixfor 的实例通过返回一个 1x1 矩阵来实现,并Num通过添加which 将右侧矩阵截断为左侧矩阵的大小(如果左侧大于右侧则错误)。fromInteger+elementwise

sum是从foldl (+) 01x1 矩阵开始,0并将列表中的所有矩阵截断为该大小。foldl1 (+)不必从整数创建矩阵,因此结果是列表中最小矩阵的大小。

此外,sum = getSum #. foldMap Sum是默认Foldable实现,但它被列表实例覆盖为sum = foldl (+) 0.

如果操作数不是相同的形状,则(如上所示)版本 0.3.1.1 的实现会生成错误,但在 0.3.2.0 版本中它假定它们是相同的形状而不检查,而在 0.3.3.0 版本中Data.Matrix+再次更改(根据评论):

-- | Perform an operation element-wise.
--   The second matrix must have at least as many rows
--   and columns as the first matrix. If it's bigger,
--   the leftover items will be ignored.
--   If it's smaller, it will cause a run-time error.
--   You may want to use 'elementwiseUnsafe' if you
--   are definitely sure that a run-time error won't
--   arise.

实现似乎与当前版本 0.3.6.1 相同


推荐阅读