SML 未捕获异常 空作业1
问题:编写一个函数 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在一个简短的列表上尝试您的解决方案的几个步骤:
您可以清楚地看到这是错误的 - 列表的元素不应该相加,并且您不能继续在每个尾部寻找相同的总和。
这意味着如果头大于或等于总和,结果为0
,否则索引多一个,而不是
hd xl
比尾部索引更多。此外,您要查找的“尾部总和”不是原始总和,而是没有
hd xl
的总和。Try a couple of steps of your solution on a short list:
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.
This means that the result is 0 if the head is greater than or equal to the sum,
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
.