I am trying to write an SML program to check if a matrix is singular. A matrix has been represented as a list of lists. Example [[1,2],[3,4],[15,50]] is a valid one but [[1,2],[1,2,3]] is not.
fun remove (l,r)=
let fun iter(front,l,i)=
if i=r then front@tl(l)
else
iter(front@[hd(l)],tl(l),i+1)
in
iter([],l,1) end;
fun removed (l,r)=
let fun iter(l,m)=if tl(l)=[]
then m@[remove (hd(l),r)]
else iter(tl(l),m@[remove (hd(l),r)])
in
iter(tl(l),[]) end;
fun nth (l,i)=let fun iter(l,c)=if i=c then hd(l) else iter(tl(l),c+1) in iter(l,1) end;
fun deter (l)=let fun iter(det,i,j)=if i=(length l)+1 then det else iter (det+j*(nth (hd(l),i))*(deter (removed(l,i))),i+1,j*(~1))
in iter(0,1,1) end
The function deter gets defined but when I give an input to it, an error of uncaught exception empty occurs. Please help me debug it.
Thanks
The problem stems from attempting to call either hd or tl on an empty list.
The best way to avoid that sort of problem, is to avoid those functions whenever possible. 99 out of 100 times, you can use pattern matching instead, and then the compiler will perform checking of whether you handle both non-empty and empty lists.
To use pattern matching on list, you use something similar to the following pattern:
Instead of
fun f ls = ... (* code where you use hd ls, tl ls *)
use
fun f (x::xs) = ... (* non-empty list; x = the head, xs = the tail *)
| f [] = ... (* empty list *)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With