[Haskell-cafe] assistance with using haskell to calculate the determinant

Carter Tazio Schonwald cartazio at yahoo.com
Sun Mar 27 00:04:55 EST 2005


I've written a simple program to calculate determinants of matrices, and 
while it executes to completion
it fails to yield a correct answer. (and yes, I know I'm using lists to 
represent matrices)

I would greatly appreciate any assistance in correcting this algorithm

--Carter Schonwald


import Prelude


first [] = []
first (a:b) = a

nth::Int->[a]->a
nth _ [] = error "list is too small"
nth 1 (a:b) = a
nth n (a:b)  = nth (n-1) b
      
takeAfter::Int->[a]->[a]
takeAfter _ [] = error "list too small"
takeAfter 0 a= a
takeAfter  1  (a:b) = b
takeAfter  n (a:b)  = takeAfter  ( n-1)  b



type Matrix = [[Rational]]


pad a  = [x++x| x<- a]


time2 []  _ = []
time2  _ [] = []
time2 (a:b) (c:d) = (a  * c):(time2 b d)


tupleProd (a,b) = a * b


altSign a = [b* (-1^num) |  b<-a, num <- [2..]]

index::Int->Int->Matrix->Rational
index a b c  = nth b (nth a c) --- ath row, bth column

slice::(Int,Int)->(Int,Int)->Matrix->Matrix
slice (a,b) (c,d) list =   let rowSliceFront = takeAfter  (a-1) list  
---  a and c are rows, b and c are columns
                in let rowSlice = take  (c-a+1) list
                  in let columnSliceFront = map (takeAfter (b-1)) rowSlice
                    in map (take  (d-b+1)) columnSliceFront


determinant::Matrix->Rational
determinant a = det (pad a) (length a)

  -- only called from determinant
det::Matrix->Int->Rational
det a 1 = index 1 1 a
det a size =let
        coeffs = altSign (first (take 1 a))
        newsize = size - 1
        leastToMax = newsize - 1        
        slices = [ slice (2,  i) (size, i + leastToMax) a | i <- 
[2..(size+1)]  ]
          in
          sum (time2  coeffs (map (\l-> det l newsize) (map (pad) 
slices))  )






More information about the Haskell-Cafe mailing list