Function 方案-将变量定义为函数的结果?
我的一个程序的开始导致一个错误。这就是问题所在。我试图将一个变量定义为递归函数的结果Function 方案-将变量定义为函数的结果?,function,functional-programming,scheme,Function,Functional Programming,Scheme,我的一个程序的开始导致一个错误。这就是问题所在。我试图将一个变量定义为递归函数的结果 (define (test n) (define (a1func i) (if (= i 1) 0 (+ (/ 1 i) (a1func (- i 1))))) (define a1 (a1func (- n 1)))) 如果你给它说(测试10),错误是: (define (test n) (define (a1func i) (if (= i 1) 0
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
(define a1 (a1func (- n 1))))
如果你给它说(测试10)
,错误是:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(define a1 (a1func(- n 1)))
a1)
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(a1func(- n 1)))
程序应用:预期程序,给定:#
;理由是:9
我以为这可以在计划中完成??思想?在纯FP语言中,计算是通过将参数传递给函数来完成的,函数返回一些值作为结果。您可以在调用
test
的函数中绑定test
的结果:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
(a1func (- n 1)))
(define (calltest x)
(define (r (test (+ 2 x))))
(- r 4))
变量通常绑定一次,不能更改。函数必须返回值,即表达式的结果,但是(define a1(a1func(-n 1))
是一个定义,而不是表达式,因此正确的代码应该是:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(define a1 (a1func(- n 1)))
a1)
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(a1func(- n 1)))
由于定义变量并立即返回它是毫无意义的,因此更正确的代码应该是:
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(define a1 (a1func(- n 1)))
a1)
(define (test n)
(define (a1func i)
(if (= i 1) 0
(+(/ 1 i) (a1func(- i 1)))))
(a1func(- n 1)))
如果方案实现支持lisp宏,则可以编写以下代码:
(define-macro (test n)
(define (a1func i)
(if (= i 1) 0
(+ (/ 1 i) (a1func (- i 1)))))
`(define a1 ,(a1func (- n 1))))
或者使用命名let
(define-macro (test n)
`(define a1 ,(let a1func ((i (- n 1)))
(if (= i 1)
0
(+ (/ 1 i) (a1func (- i 1)))))))
您的代码不完整。你能发布其余的吗?顺便说一句,你的代码在最后一行的末尾缺少一个结束符
)
。问题是我需要将a1绑定到a1func的结果值。我将在程序后面使用值a1以及变量n(原始输入)。然后您应该在模块顶部定义a1
,因为在原始定义中a1
在函数test
的范围内,否则其他函数无法使用它。如果您在模块顶部定义了a1
,那么您应该以相同的方式定义a1func
,这样就可以在test
的范围之外访问它。我将对此进行另一次尝试。。我不知道我为什么会有这样的问题。所以我又从头开始。。我有一个取值为n的程序。这个程序需要运行几个数学运算。其中一些操作使用早期操作中的值。例如:(定义(a1func1n)(let*((e10))(let*((i(-n1)))(如果(=n1)0(+(/1i)(a1func1(-n1щщ))))。。。我得到了正确的结果,但需要全局存储。在以后的几个函数中使用。@DJPlayer:在FP中,通常不全局存储变量,函数程序只是对函数的一系列[mutual]调用,当每个函数对给定参数执行一些计算并返回结果时。你应该知道,如果你给一个函数相同的参数,它总是返回相同的结果。G如果您给它2
,3
,并且它计算一个总和,则无论调用多少次,它都将始终返回5
。您可能有全局变量(使用定义),但它们不能更改(如果我们讨论的是纯FP)。