SML 未捕获异常为空
我对 SML 很陌生,正在尝试实现选择排序。然而,我遇到了一个未捕获的空错误,似乎不明白为什么。
fun removeMin lst =
let
val (m, l) = removeMin(tl lst)
in
if null (tl lst) then
(hd lst, [])
else if hd lst < m then
(hd lst, tl lst)
else
(m, hd lst::l)
end;
fun selectionSort [] = []
| selectionSort lst =
let
val (m, l) = removeMin(lst)
in
m::selectionSort(l)
end;
我希望得到有关我的错误在哪里以及如何解决的建议。
I am quite new to SML and am trying to implement a selection sort. I am running into an uncaught empty error however and can't seem to see why.
fun removeMin lst =
let
val (m, l) = removeMin(tl lst)
in
if null (tl lst) then
(hd lst, [])
else if hd lst < m then
(hd lst, tl lst)
else
(m, hd lst::l)
end;
fun selectionSort [] = []
| selectionSort lst =
let
val (m, l) = removeMin(lst)
in
m::selectionSort(l)
end;
I would appreciate suggestions as to where my mistake is and how to fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的递归中没有基本情况。立即
removeMin
使用
lst
的尾部调用removeMin
。最终lst
将是空列表和
tl lst
将失败并出现Empty
异常。所以你必须确定递归何时应停止并将此情况添加到
removeMin
。您实际上已经在函数中确定了这个基本情况:
if null (tl lst) then (hd lst, [])
。但这种情况应该检查一下在递归调用之前。通过重组你的功能并获得
使用模式匹配结构消除对
hd
和tl
的调用这就是我得到的:
There is no base case in your recursion.
removeMin
immediatelycalls
removeMin
with the tail oflst
. Eventuallylst
will bethe empty list and
tl lst
will fail with anEmpty
exception. So youhave to identify when you recursion should stop and add this case to
removeMin
.You have actually identified this base case in your function:
if null (tl lst) then (hd lst, [])
. But this case should be checked rightbefore the recursive call. By reorganising your function and getting
rid of calls to
hd
andtl
by using pattern matching constructsthis is what I get: