方案 - 将变量定义为函数的结果? [英] Scheme - define variable as the result of a function?

查看:100
本文介绍了方案 - 将变量定义为函数的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个程序的开始会导致错误。这是问题领域。我试图定义一个变量作为递归函数的结果。

 (define(test n)
( define(a1func i)
(if(= i 1)0
(+(/ 1 i)(a1func( - i 1)))))
(define a1(a1func( - 如果你要给它说(test()),那么你可以使用 10)错误是:

lockquote

程序应用程序:期望的程序,给定: #<未定义> ;参数是:9


我认为这可以在Scheme中完成?在纯FP语言中,计算是通过将参数传递给函数完成的,后者返回一些值作为结果。您可以在名为 test 的函数中绑定 test 的结果:

 (define(test n)
(define(a1func i)
(if(= i 1)0
(+ 1)(a1func(-i 1)))))
(a1func( - n 1)))

(define(calltest x)
(define(r测试(+ 2 x))))
( - r 4))

变量通常绑定一次,无法更改。一个函数必须返回表达式的值,但是(define a1(a1func( - n 1)))是一个定义,而不是一个表达式,所以正确代码可以是:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ (= 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)))


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?

解决方案

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 called 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))

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:

(define (test n)
  (define (a1func i)
    (if (= i 1) 0
        (+(/ 1 i) (a1func(- i 1))))) 
  (define a1 (a1func(- n 1)))
  a1)

And since defining variable and immediate returning it is meaningless, a more correct code would be:

(define (test n)
  (define (a1func i)
    (if (= i 1) 0
        (+(/ 1 i) (a1func(- i 1))))) 
  (a1func(- n 1)))

这篇关于方案 - 将变量定义为函数的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆