coder4lyf
coder4lyf

Reputation: 927

Multiply function in F# always returns with failwith

I'm trying to write a function in F# for multiplying 2 matrices together. It uses a transpose function that finds the transpose of a given matrix.

let rec transpose = function
   | [] -> failwith "Error, no matrix supplied"
   | xs when List.head xs = [] -> []
   | xs -> List.map (fun n -> List.head n) xs :: transpose
           (List.map(fun n -> List.tail n) xs);;



 let rec multiply = function
    |([], []) -> []
    |([], ys) -> failwith "Empty matrix"
    |(xs, []) -> failwith "empty matrix"
    |(x::xs, ys) -> let t = transpose ys
                     List.map(fun n -> inner x n) t :: multiply(xs,ys);;

No matter what the input is, my multiply function always executes "failwith" if I were to return with [0] however, instead of failwith, the function works perfectly. But I feel 0 is incorrect when multiplying a matrix with an empty one so I want to fix this and be able to output error if that is the case.

Upvotes: 0

Views: 100

Answers (1)

John Palmer
John Palmer

Reputation: 25516

Your problem is in the recursion - you do:

multiply(xs,ys)

This will happen until xs=[] when you will get a fail.

The best solution is probably to have a wrapper function - something like

let multiply a b = 
    check a
    check b
    let rec actualmultiply = ...
    actualmultiply a b

Upvotes: 3

Related Questions