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

Henning Thielemann lemming at henning-thielemann.de
Tue Mar 29 06:54:46 EST 2005


On Sun, 27 Mar 2005, Carter Tazio Schonwald wrote:

> 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

'head' on lists of lists without an error empty lists?

> 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

Is this case necessary?

> takeAfter  n (a:b)  = takeAfter  ( n-1)  b

Is it the same like 'drop'?

> type Matrix = [[Rational]]
>
>
> pad a  = [x++x| x<- a]

maybe 'cycle' helps

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

zipWith (*)

?

> tupleProd (a,b) = a * b

uncurry (*)


...





Here is another implementation of determinant:

{- successively select elements from xs and remove one in each result list -}
removeEach :: [a] -> [[a]]
removeEach xs =
   zipWith (++) (List.inits xs) (tail (List.tails xs))

alternate :: (Num a) => [a] -> [a]
alternate = zipWith id (cycle [id, negate])

det :: (Num a) => [[a]] -> a
det [] = 1
det m  = sum (alternate
                 (zipWith (*) (map head m)
                     (map det (removeEach (map tail m)))))





More information about the Haskell-Cafe mailing list