Question

#lang eopl

  (define (expo  base n  )
         (cond( (or  (= base 1) (= n 0) ) 1)
                  (else ( (* base (expo(base (- n 1))) )   ) )))

-> (enter! "expo.rkt")
"expo.rkt"> (expo (2 1) )
; application: not a procedure;
;  expected a procedure that can be applied to arguments
;   given: 2
; [,bt for context]

I am trying to create a simple recursive exponentiation, but I get the error above. Code is self-explanatory. I am a newbie in Racket programming. I have been reading the manuals, but can't find my error. Supposedly, it shows the error because my function returns a void and not a procedure, but I don't see why it would return void. I am returning 1 or a computation. Help, please :/

Was it helpful?

Solution

You have several misplaced parentheses. This should solve the errors:

(define (expo base n)
  (cond ((or (= base 1) (= n 0)) 1)
        (else (* base (expo base (- n 1))))))

And this is how you call it:

(expo 2 3)
=> 8

For the record: in Scheme a pair of parentheses means function application, so when you write (2 3) the interpreter thinks that 2 is a function and 3 is its argument ... clearly that won't work.

So you'll have to be very careful where you put those (), they make all the difference in the world! To make things easier use a good IDE with bracket matching and nice syntax coloring, and be extra tidy with the indentation. As suggested by @dyoo in the comments, DrRacket is an excellent choice.

OTHER TIPS

When you call the function, you want to write

(expo 2 1)

rather than

(expo (2 1))

Same in the definition of the recursive function's definition.

In addition, this part have double brackets, which is unnecessary.

( (* base (expo(base (- n 1))) )

The cond syntactic form is best used when a) you have more than two clauses or b) you have a sequence of commands/expressions to perform for one or more clauses. Those two cases don't apply to your code. Thus, you'd have clearer code (easier to understand; easier to get correct) using if as such:

(define (expo base n)
  (if (or (= base 1) (= n 0))
      1
      (* base (expo base (- n 1)))))

Also, study the spacing and indentation of some 'good' code; it will help your understanding tremendously.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top