CL-USER> (a-sum 0 3)

->> 6

I wrote this program :

(defun a-sum (x y) 
  (if (and (> x -1) (> y -1)) 
    (do ((i 0 (1+ i))
         (sum 0) 
         (num x))
        ((equal i (+ (- y x) 1)))
      (setq sum (+ sum num))
      (setq num (+ num 1)) 
      sum) 
    (print " NOPE")))

put if I run it in the terminal it returns nil and not the answer stated above; can someone help with the problem so it returns the value then Boolean.

2

There are 2 best solutions below

0
CL-USER On

Consider what value(s) a function returns. It's the value of the last form evaluated. In your case, that appears to be a do or maybe a setq or print (It's difficult to read as it's formatted now, and I don't have question edit privileges).

In short, the form that's returning the value for the function looks to be one evaluated for side-effects instead of returning a value.

0
coredump On

DO,DO* Syntax

The entry for DO,DO* says that the syntax is as follows:

do ({var | (var [init-form [step-form]])}*)
   (end-test-form result-form*) 
  declaration* 
  {tag | statement}*

The body is used as a list of statements and no intermediate value in this body is used as the result form of the do form. Instead, the do form evaluates as the last expression in result-form*, which defaults to nil.

 (do ((i 0 (1+ i))
      (sum 0) 
      (num x))
      ((equal i (+ (- y x) 1)) 
       ;;; RESULT FORMS HERE
      )
    (setq sum (+ sum num))  ;; (*)
    (setq num (+ num 1))    ;; (*)
    sum                     ;; (*)
 ) 

All the expressions marked commented (*) above are used for side-effects only: the result of their evaluation is unused and discarded.

Problem statement

It is not clear to me what Σpi=ni means, and your code does not seem to compute something that could be expressed as that mathematical expression.

One red flag for example is that if (+ (- y x) 1) is negative (i.e. if y < x-1, for example y=1,x=3), then your loop never terminates because i, which is positive or null, will never be equal to the other term which is negative.

I would try to rewrite the problem statement more clearly, and maybe try first a recursive version of your algorithm (whichever is easier to express).

Remarks

Please indent/format your code.

Instead of adding setq statements in the body, try to see if you can define them in the iteration clauses of the loop (since I'm not sure what you are trying to achieve, the following example is only a rewrite of your code):

(do ((i 0 (1+ i))
     (sum 0 (+ sum num)
     (num x (1+ num))
    (... sum))