方案 - 将变量定义为函数的结果?
我的一个程序的开头导致错误。这是问题所在。我试图将变量定义为递归函数的结果。
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
(define a1 (a1func (- n 1))))
如果你给它说 (test 10)
错误将是:
过程应用:预期过程,给定:
#
;参数为:9
我认为这可以在计划中完成?想法?
The beginning of one of my programs results in an error. This is the problem area. I am trying to define a variable as the result of a recursive function.
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
(define a1 (a1func (- n 1))))
if you were to give it say (test 10)
the error would be:
procedure application: expected procedure, given:
#<undefined>
; arguments were: 9
I assumed this could be done in Scheme?? ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在纯 FP 语言中,计算是通过将参数传递给函数来完成的,函数会返回一些结果。您可以在调用
test
的函数中绑定test
的结果:变量通常绑定一次,不能更改。函数必须返回值,即表达式的结果,但是
(define a1 (a1func(- n 1)))
是一个定义,而不是一个表达式,因此正确的代码是:定义变量并立即返回它是没有意义的,更正确的代码是:
In pure FP languages computations are done passing parameters to functions, which return some values as a result. You could bind the result of
test
in the function which calledtest
:Variables usually bound once and cannot be changed. A function must return the value, a result of expression, but
(define a1 (a1func(- n 1)))
is rather a definition, not an expression, so the correct code would be:And since defining variable and immediate returning it is meaningless, a more correct code would be:
如果你的方案实现支持 lisp 宏,那么你可以这样写:
或者使用命名的 let
If your scheme implementation support lisp macros then you can write this:
or using named let