我有以下函数来获取矩阵的幂
X^0 = 单位矩阵,
X^1 =X;
X^2 = X'X;
X^3 = X X' X;
X^4 = X' X X' X ......
我尝试了以下功能:
import Numeric.Container
import Numeric.LinearAlgebra
mpow :: Field t => (Matrix t) -> Integer -> (Matrix t)
mpow x 0 = ident $ cols x
mpow x 1 = x
mpow x n =
if (mod n 2) == 0 then
multiply (trans x) (mpow x $ n - 1)
else
multiply x (mpow x $ n - 1)
是否可以不使用 if-else 语句重写此函数?
最佳答案
是的,你可以使用守卫。但通常它会在 Haskell 中编译成相同的内部表示。
import Numeric.Container
import Numeric.LinearAlgebra
mpow :: Field t => (Matrix t) -> Integer -> (Matrix t)
mpow x 0 = ident $ cols x
mpow x 1 = x
mpow x n | (mod n 2) == 0 = multiply (trans x) (mpow x $ n - 1)
| otherwise = multiply x (mpow x $ n - 1)
关于不使用 if-else 语句的 haskell 矩阵幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21152669/