Emma
Emma

Reputation: 323

Out of Bounds Subscript

I am getting the sml Subscript out of bounds error,in my code below.I cannot figure out where the error is.Can someone help?

fun extract_Bools nil = nil
  | extract_Bools ((_,x)::xs) = let
                 val  Boolists = x::extract_Bools(xs)
                 val Len = length(Boolists)
             in
                 List.tabulate(Len,fn i => map (fn Boolists =>     (List.nth(Boolists,i))) Boolists)
             end;

well the function takes [([1,2,3],[false,false]),([4],[true,false]),([2,3,4,5,6],[false,false]),([23,45,23],[true,true])] for example and should return a bool list list in which elements at similar positions will be put in one list for example we should return [[false,true,false,true],[false,false,false,true]]

Upvotes: 0

Views: 606

Answers (1)

Tayacan
Tayacan

Reputation: 1826

The error is in the computation of Boolists. You call extract_Bools recursively, expecting it to give you the second elements of all the tuples in the list, but extractBools does more than that. You need a second function for pulling the boolean lists out of the original list.

Additionally, Len is wrong - it is not the length of the list of lists you want, but the length of the lists inside. I have assumed here that all boolean lists will always have the same length, and that given an empty list, you want to return an empty list.

local
  fun getBools xs = map (fn (_,b) => b)  xs
in  
  fun extractBools xs =
  let
    val blists = getBools xs
    val len = case blists of
                  []      => 0
                | (x::xs) => length x
  in
    List.tabulate(len, fn i => map (fn l => List.nth(l,i)) blists)
  end
end

I've renamed some variables - it is a convention in SML to let variable names start with a lower case letter, and to write names in camel case instead of using underscores.

Upvotes: 1

Related Questions