lisp - Code bug Lambda expression -


i m trying write lisp function test if number prime or not. received lambda expression error (i ve searched previouslly answered questions related this) cannot find solution.

(defun prime(n)  (       (defvar '(*ok* nil) (*i* nil) (*d* nil)     (setf *ok* 1)      (loop *i* 1 (sqrt n)        (      (if (= (mod n *d*) 0)             (setf *ok* 0))          )      )      (if (= *ok* 1)             (format t "numarul prim")             (format t "numarul nu este prim")          )  ) 

)

i don't mean sound rude do need read decent common lisp tutorial; code more "you can code c in language", "i didn't dynamic variable stuff" thrown in.

to show want, here's how write logic:

(defun prime (n)   (if (loop          2 (sqrt n)          when (zerop (mod n i)) return nil          (return t))       "numarul prim"       "numarul nu este prim")) 

testing:

cl-user> (loop    2 20    (format t "~a ~a~%" (prime i))) 2 numarul prim 3 numarul prim 4 numarul nu este prim 5 numarul prim 6 numarul nu este prim 7 numarul prim 8 numarul nu este prim 9 numarul nu este prim 10 numarul nu este prim 11 numarul prim 12 numarul nu este prim 13 numarul prim 14 numarul nu este prim 15 numarul nu este prim 16 numarul nu este prim 17 numarul prim 18 numarul nu este prim 19 numarul prim 20 numarul nu este prim nil 

edit 1 - using local variable:

(defun prime (n)   (let ((is-prime t))     (loop        2 (sqrt n)        when (zerop (mod n i))        (setf is-prime nil))     (if is-prime        "numarul prim"        "numarul nu este prim"))) 

edit 2 - "how can sum these prime numbers"

let's go true function - in case, predicate indicates if number prime (returns t) or not (returns nil):

(defun prime (n)   (loop      2 (sqrt n)      when (zerop (mod n i)) return nil      (return t)))  cl-user> (prime 2) t cl-user> (prime 3) t cl-user> (prime 4) nil 

and second function collects primes between lower , upper bound list:

(defun primes (pfrom pto)   (loop      pfrom pto      when (prime i) collect i))  cl-user> (primes 2 20) (2 3 5 7 11 13 17 19) 

then need to

cl-user> (reduce '+ (primes 2 20)) 77 

Comments