SML 未捕获异常 空作业1

发布于 2025-01-15 05:49:56 字数 549 浏览 4 评论 0原文

问题:编写一个函数 number_before_reaching_sum,它接受一个名为 sum 的 int,您可以假设它 是正数,并且是一个 int 列表,您可以假设它包含所有正数,并返回一个 int。 您应该返回一个 int n ,使得列表的前 n 个元素相加小于总和,但第一个 列表中的 n + 1 个元素相加等于或大于总和。假设整个列表的总和大于传入的值 价值;如果不是这种情况,发生异常也是可以的。

我对 SML 很陌生,无法发现这个简单的表达式有什么问题。错误信息请帮我调试下面的代码

fun number_before_reaching_sum (sum:int, xl: int list) =
    if hd xl = sum
    then 0
    else
    (hd xl) + number_before_reaching_sum(sum, (tl xl))

Question: Write a function number_before_reaching_sum that takes an int called sum, which you can assume
is positive, and an int list, which you can assume contains all positive numbers, and returns an int.
You should return an int n such that the first n elements of the list add to less than sum, but the first
n + 1 elements of the list add to sum or more. Assume the entire list sums to more than the passed in
value; it is okay for an exception to occur if this is not the case.

I am quit new on SML, and coudn't find out anything wrong with this simple exprssion. The error message Please help me to debug the code below

fun number_before_reaching_sum (sum:int, xl: int list) =
    if hd xl = sum
    then 0
    else
    (hd xl) + number_before_reaching_sum(sum, (tl xl))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

时光礼记 2025-01-22 05:49:56

在一个简短的列表上尝试您的解决方案的几个步骤:

    number_before_reaching_sum (6, [2,3,4])
--> if 2 = 6
    then 0
    else 2 + number_before_reaching_sum(6, [3,4])
--> 2 + if 3 = 6
        then 0
        else 3 + number_before_reaching_sum(6, [4])
--> ...

您可以清楚地看到这是错误的 - 列表的元素不应该相加,并且您不能继续在每个尾部寻找相同的总和。

您应该返回一个 int n ,使得列表的前 n 个元素相加小于 sum,但列表的前 n + 1 个元素相加等于或大于 sum。

这意味着如果头大于或等于总和,结果为0

if hd xl >= sum
then 0

,否则索引多一个,而不是hd xl 比尾部索引更多。
此外,您要查找的“尾部总和”不是原始总和,而是没有 hd xl 的总和。

else 1 + number_before_reaching_sum(sum - hd xl, tl xl)

Try a couple of steps of your solution on a short list:

    number_before_reaching_sum (6, [2,3,4])
--> if 2 = 6
    then 0
    else 2 + number_before_reaching_sum(6, [3,4])
--> 2 + if 3 = 6
        then 0
        else 3 + number_before_reaching_sum(6, [4])
--> ...

and you see pretty clearly that this is wrong - the elements of the list should not be added up, and you can't keep looking for the same sum in every tail.

You should return an int n such that the first n elements of the list add to less than sum, but the first n + 1 elements of the list add to sum or more.

This means that the result is 0 if the head is greater than or equal to the sum,

if hd xl >= sum
then 0

Otherwise, the index is one more, not hd xl more, than the index in the tail.
Also the "tail sum" you're looking for isn't the original sum, but the sum without hd xl.

else 1 + number_before_reaching_sum(sum - hd xl, tl xl)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文