方案语法帮助:使用我在另一个程序中定义的函数
我创建了两个函数来帮助我解决子集和问题。不过我似乎遇到了错误。它告诉我,我正在向 list-sum
传递两个参数。我已经在这个程序上闲逛了几个小时了。我想知道是否有人能发现这个问题。
这是我的 list-sum
:
(define list-sum
(lambda(lst)
(cond
((null? lst) 0)
((pair? (car lst))
(+(list-sum (car lst)) (list-sum (cdr lst))))
(else
(+ (car lst) (list-sum (cdr lst)))))))
这是我使用 list-sum
的函数:
(define ssum
(lambda (n l)
(cond
((null? l) #f)
((=(-(- n (car l))(list-sum l)) 0) l)
((ssum (cons (car l)) (cdr (cdr l))))
(else (ssum n (cdr l))))))
它告诉我,我已经用一个调用了“compound-procedure #(number) ssum”论证并且它需要两个论证。我将其传递为 (ssum 8 (list 1 3 5 7))
。
我的问题是:
- 我的功能设置正确吗?
- 有没有更简单的求和方法 我的
ssum
中列表的数字? - 我对Scheme也很陌生。如果你看到 缩短代码的明显方法, 请随时纠正我。
I have created two functions to help me solve my Subset sum problem. I seem to be getting an error though. It tells me that I am passing two arguments to list-sum
. I've been fooling around with this program for several hours now. I was wondering if anyone could spot the problem.
This is my list-sum
:
(define list-sum
(lambda(lst)
(cond
((null? lst) 0)
((pair? (car lst))
(+(list-sum (car lst)) (list-sum (cdr lst))))
(else
(+ (car lst) (list-sum (cdr lst)))))))
This is my function that uses list-sum
:
(define ssum
(lambda (n l)
(cond
((null? l) #f)
((=(-(- n (car l))(list-sum l)) 0) l)
((ssum (cons (car l)) (cdr (cdr l))))
(else (ssum n (cdr l))))))
It tells me that I have called "compound-procedure #(number) ssum" with one argument and that it requires two arguments. I am passing it as (ssum 8 (list 1 3 5 7))
.
My questions are:
- Have I set up my functions correctly?
- Is there an easier method of summing
the numbers of a list inside myssum
? - I am also very new to Scheme. If you see
an obvious way of shortening the code,
please feel free to correct me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我强烈建议你尝试racket,它的IDE有这个很棒的调试器,只有ODB 可以说更好。
我没有深入研究您的代码应该如何工作,因为
((ssum (cons (car l)) (cdr (cdr l)))) 中实际上有几个错误
line:您仅使用一个参数调用 cons,但此 cond 子句中也只有一种形式,而它后面应该有一个测试和至少一个表达式。I strongly recommend you to try racket, its IDE has this awesome debugger that only the ODB could claim being better.
I didn't dig too deep in how your code is supposed to work, because there are actually several errors in the
((ssum (cons (car l)) (cdr (cdr l))))
line: you callcons
with only one argument, but you also have only one form in thiscond
clause, whereas it should have a test and at least one expression behind.list-sum 函数可以优化。首先,可以连接两个
(list-sum (cdr lst))
表达式,并且可以将三个(car lst)
表达式减少为一个:The list-sum function can be optimized. First it is possible to join the two
(list-sum (cdr lst))
expressions and it is possible to reduce the three(car lst)
expressions to one: