0

I am trying to write a recursive code to do x^y but the problem no mater how I update the code it gives me an error.

The Code:

    (defun power(x y) (if(> y 0) (* x (power(x (- y 1)))) (1)))

Error:

CL-USER 11 : 5 >Power 2 3
Error: Undefined operator X in form (X (- Y 1)).

Error:

CL-USER 11 : 5 >power(2 3)
Illegal argument in functor position: 2 in (2 3).

5 Answers 5

13

You're calling the function in the wrong way. In lisps function calls have the form:

(f a b c) 

not

f(a b c)

You had (power (x (- y 1))) in your recursive definition, which in turn had (x (- y 1)) hence the error: x is not a function.

Use (power x (- y 1)) so your definition becomes:

(defun power (x y)
   (if (> y 0)
      (* x
           (power x (- y 1))) 
      1))

and call it as (power 2 3)

Sign up to request clarification or add additional context in comments.

2 Comments

Replace (1) with 1 in the else branch, and it will be correct.
@TerjeD. well spotted!
6

To expand slightly on the previous (correct) answer, this version uses some idiomatic functions:

(defun power (x y)
  (if (plusp y)
    (* x (power x (1- y)))
    1))

Comments

2

You cannot use parenthesis for grouping since CL thinks you want to call function x and function 1. Remove the excess like this:

 (defun power(x y) 
     (if (> y 0) 
         (* x (power x (- y 1)))
         1))

Parenthesis goes on the outside, just as in your function:

 (power 2 3) ;==> 8

Comments

1

When you write (X ...) in a Lisp expression, you are asserting that X is a function to be called on the arguments ....

Your problem is you have too many parentheses in your expression. When you write (power (x .. you've made this assertion. Write (power x ... instead.

Comments

0

You're calling, among others, this code:

(power (x (- y 1)))

So power is called with (x (- y 1)) as a parameter. Are you sure you want to call x as a function?

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.