简体   繁体   中英

Trying to create a recursive function in scheme?

I'm having a little trouble creating a recursive function in Scheme. I need to create a function called foo(x) that recursively does the addition of all the powers. 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. Else then return x^x-1 + foo(x-1) Here's what I have so far for my function:

(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) . 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:

(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. 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.

The rules of Scheme are that parentheses matters . x and (x) are two totally different things. The first x can be any value, but (x) is an application so x have to evaluate to a procedure. 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.

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. Seeing cond I expect either side effects or more than one predicate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM