SML 未捕获异常为空

发布于 2025-01-14 10:57:20 字数 449 浏览 4 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

耀眼的星火 2025-01-21 10:57:20

您的递归中没有基本情况。立即removeMin
使用 lst 的尾部调用 removeMin。最终lst将是
空列表和 tl lst 将失败并出现 Empty 异常。所以你
必须确定递归何时应停止并将此情况添加到
removeMin

您实际上已经在函数中确定了这个基本情况:if null (tl lst) then (hd lst, [])。但这种情况应该检查一下
在递归调用之前。通过重组你的功能并获得
使用模式匹配结构消除对 hdtl 的调用
这就是我得到的:

fun removeMin [] = raise Empty  (* should not be called with an empty list *)
  | removeMin [x] = (x, [])     (* base case of the recursion *)
  | removeMin (x :: tl) = let
      val (m, l) = removeMin tl
  in
      if x < m
      then (x, tl)
      else (m, x :: l)
  end;

fun selectionSort [] = []
  | selectionSort lst = let
      val (m, l) = removeMin(lst)
  in
      m :: selectionSort(l)
  end;

selectionSort [3, 2, 12, 4];

There is no base case in your recursion. removeMin immediately
calls removeMin with the tail of lst. Eventually lst will be
the empty list and tl lst will fail with an Empty exception. So you
have 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 right
before the recursive call. By reorganising your function and getting
rid of calls to hd and tl by using pattern matching constructs
this is what I get:

fun removeMin [] = raise Empty  (* should not be called with an empty list *)
  | removeMin [x] = (x, [])     (* base case of the recursion *)
  | removeMin (x :: tl) = let
      val (m, l) = removeMin tl
  in
      if x < m
      then (x, tl)
      else (m, x :: l)
  end;

fun selectionSort [] = []
  | selectionSort lst = let
      val (m, l) = removeMin(lst)
  in
      m :: selectionSort(l)
  end;

selectionSort [3, 2, 12, 4];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文