[英]Trying to create a recursive function in scheme?
I'm having a little trouble creating a recursive function in Scheme. 我在Scheme中创建递归函数时遇到了一些麻烦。 I need to create a function called foo(x) that recursively does the addition of all the powers. 我需要创建一个名为foo(x)的函数,该函数以递归的方式添加所有能力。 For example foo(5) would be 5^4 + 4^3 + 3^2 + 2^1 + 1^0 = 701. The stopping condition is if x = 0 then return zero. 例如foo(5)将为5 ^ 4 + 4 ^ 3 + 3 ^ 2 + 2 ^ 1 + 1 ^ 0 =701。停止条件是x = 0时返回零。 Else then return x^x-1 + foo(x-1) Here's what I have so far for my function: 否则返回x ^ x-1 + foo(x-1)这是我到目前为止对函数的了解:
(define (foo x)
(cond ((zero? x) 0)
(else (+(expt(x (- x 1)))foo(- x 1)))))
You just have to be more careful with the parentheses, in particular notice that the correct way to call a procedure is like this: (foo x)
, instead of this: foo(x)
. 您只需要注意括号,尤其要注意,调用过程的正确方法是这样的: (foo x)
,而不是这样: foo(x)
。 This should work: 这应该工作:
(define (foo x)
(cond ((zero? x) 0)
(else (+ (expt x (- x 1))
(foo (- x 1))))))
(foo 5)
=> 701
Allow me to ident the code. 请允许我识别代码。 I just pasted it in DrRacket and hit CTRL+I then put the arguments to +
on one line each: 我只是将其粘贴到DrRacket中,然后按CTRL +,然后将参数分别加到+
上一行:
(define (foo x)
(cond ((zero? x) 0)
(else (+ (expt (x (- x 1)))
foo
(- x 1)))))
So the base case is ok, but your default case looks very off. 因此,基本情况尚可,但是您的默认情况看起来很不正常。 x
is treated as a procedure since it has parentheses around it and -
also uses x
as if it's a number. x
被视为过程,因为x
周围带有括号,并且-
也将x
当作数字使用。 It can't be both. 不能两者兼有。
foo
is not applied since it doesn't have parentheses around it so it evaluates to a procedure value, while +
would expect all its arguments to be numeric. foo
不被应用,因为它周围没有括号 ,因此它求值为过程值,而+
期望其所有参数均为数字。
The rules of Scheme are that parentheses matters . Scheme的规则是括号很重要 。 x
and (x)
are two totally different things. x
和(x)
是完全不同的两件事。 The first x
can be any value, but (x)
is an application so x
have to evaluate to a procedure. 第一个x
可以是任何值,但是(x)
是应用程序,因此x
必须对过程求值。 Some exceptions are for special forms you need to know by heart like cond
, and define
but rather than that it's very important to know you change the meaning of a program by adding parentheses. 有些例外是特殊的形式,您需要像cond
这样的cond
,并对其进行define
但要知道,您要通过添加括号来更改程序的含义非常重要,这并不是非常重要的。
The correct definition of your procedure might be: 您的过程的正确定义可能是:
(define (foo x)
(if (zero? x)
0
(+ (expt x (- x 1))
(foo (- x 1)))))
(foo 5) ; ==> 701
Here I've changed cond
to if
since none of cond
s features were used. 在这里,我已经将cond
更改为if
因为没有使用cond
的功能。 Seeing cond
I expect either side effects or more than one predicate. 看到cond
我期望副作用或多个谓词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.