Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell matrix power without using if-else statement

I have the following function to obtain power of a matrix

X^0 = identity matrix, X^1 =X;
X^2 = X'X;
X^3 = X X' X;
X^4 = X' X X' X ......

I tried with following function:

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)

Is it possible to rewrite this function without using the if-else statement ?

like image 755
Gong-Yi Liao Avatar asked Sep 22 '26 05:09

Gong-Yi Liao


1 Answers

Yes, you could use guards. But quite often it will compile into the same internal representation in 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)
like image 169
Stephen Diehl Avatar answered Sep 24 '26 20:09

Stephen Diehl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!