0

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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.