超出界限

时间:2013-12-04 16:35:20

标签: sml

我在下面的代码中得到了sml下标超出界限错误。我无法弄清楚错误在哪里。可以帮助某人吗?

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;

该函数以[([1,2,3],[false,false]),([4],[true,false]),([2,3,4,5,6],[false,false]),([23,45,23],[true,true])]为例,应返回bool list list,其中类似位置的元素将放在一个列表中 例如,我们应该返回[[false,true,false,true],[false,false,false,true]]

1 个答案:

答案 0 :(得分:1)

错误在于Boolists的计算中。你递归地调用extract_Bools,期望它给你列表中所有元组的第二个元素,但是extractBools做的不止于此。你需要第二个函数来从原始列表中提取布尔列表。

另外,Len是错误的 - 它不是你想要的列表长度,而是里面列表的长度。我假设所有布尔列表总是具有相同的长度,并且给定一个空列表,你想返回一个空列表。

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

我已经重命名了一些变量 - 它是SML中的一种约定,它允许变量名以小写字母开头,并以驼峰形式写名,而不是使用下划线。

相关问题