Frage

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 ?

War es hilfreich?

Lösung

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)

Andere Tipps

As freyrs mentioned, guards and if statements are exactly equivalent as they are both converted to case of when you compile your code. But, you can still get rid of them:

mpow' :: Field t => (Matrix t) -> Integer -> (Matrix t) 
mpow' x 0 = ident $ cols x 
mpow' x 1 = x
mpow' x n = multiply (head (drop n' fs) $ x) (mpow' x $ n - 1)
    where fs = [trans, id]
          n' = fromInteger (mod n 2)

However, this isn't more concise, nor does it better communicate what your function is doing to the reader. So don't do this, unless you really hate conditionals.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top