nothing
nothing

Reputation: 19

Lisp function call syntax

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

Upvotes: 0

Views: 14656

Answers (5)

Sylwester
Sylwester

Reputation: 48745

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

Upvotes: 2

soulcheck
soulcheck

Reputation: 36767

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)

Upvotes: 13

Lars Brinkhoff
Lars Brinkhoff

Reputation: 14295

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

Upvotes: 6

Ira Baxter
Ira Baxter

Reputation: 95334

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.

Upvotes: 1

user434817
user434817

Reputation:

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?

Upvotes: 0

Related Questions