我正在尝试编写一些简单的反向替换矩阵代码。为此,我编写了一个fold
与行折叠的运算符。
这是函数的非泛型类型签名及其实现:
foldMatrixByRow :: (Array D DIM1 Double -> Array D DIM1 Double -> Int -> Array D DIM1 Double)
-> Array D DIM1 Double
-> Array U DIM2 Double
-> Array D DIM1 Double
foldMatrixByRow f intial mat = foldMatrixByRowUtil f intial (mat, 0)
where foldMatrixByRowUtil f initial (mat, i)
| i == n = initial
| otherwise = foldMatrixByRowUtil f result (mat, i + 1)
where result = f matRow initial i
matRow = delayNRow mat i
(Z :. n :. _) = extent mat
- repa's 等与上述折叠的区别在于
foldS
,foldP
折叠函数将 2 个DIM1
延迟数组作为参数。 - 更重要的是,为了帮助循环融合,它返回一个延迟数组 (
Array D DIM1 Double
)。
以下是反向替换的代码
backsubstitution :: Array U DIM2 Double -> Array U DIM1 Double -> Array D DIM1 Double
backsubstitution mat bs = foldMatrixByRow f initial mat
where
f matRow sols i = fromFunction (extent bs) intArr
where
intArr (Z :. j) | i == j = rowComp | j < i = 0.0 | otherwise = sols R.! (Z :. j)
intc = ((bs ! (Z :. i)) - (rowComp)) / (matRow ! (Z :.i))
rowComp = sumAllS $ traverse2Backwards matRow sols g
g m s (i', _) = if i < i' then m * s else 0.0
initial = fromFunction (extent bs) (\ _ -> 0)
- 为了帮助循环融合我,故意使
initial
延迟。matRow
计算delayNRow
它还计算一个延迟数组(delayNRow
代码在下一个项目符号之后提供)。 fromFunction
类型签名肯定会返回一个延迟的数组。delayNRow :: Array U DIM2 Double -> Int -> Array D DIM1 Double
delayNRow arr n = R.slice arr (Any :. n :. All)
但问题是:
为什么我会收到以下错误:
Couldn't match type `D' with `U'
Expected type: Array D DIM1 Double -> Array D DIM1 Double -> Int -> Array D DIM1 Double
Actual type: Array U DIM1 Double -> Array U DIM1 Double -> Int -> Array D DIM1 Double
In the first argument of `foldMatrixByRow', namely `f'
In the expression: foldMatrixByRow f initial mat
In an equation for `backsubstitution':
In an equation for `backsubstitution':
backsubstitution mat bs
= foldMatrixByRow f initial mat
where
f matRow sols i
= fromFunction (extent bs) intArr
where ...
tldr;
为什么我得到输入到数组的错误f
,backsubstitution
而U
我为它们提供延迟的数组(D
)。