Reputation: 653
I want an integer x, that increases by one every time a function is called.
I was told to use (defvar x) to declare the variable, but does this declare it as an int?
And also, is there a Lisp equivalent to x++ (x = x + 1) that I can use at the end of the function?
Thanks a lot.
Upvotes: 0
Views: 190
Reputation: 48745
You don't need to declare what type it is. Just set it to a number.
Use the macro incf
to change the binding to the successor of the current binding.
You don't need to have it as a global. You can have a closed over variable to update. Eg.
(let ((call-count 0))
;; create my-func in the scope of call-count
(defun my-func (arg)
(if (eq arg 'get) ;; if the argument is the symbol get
call-count ;; return call-count
(progn ;; else we do first
(incf call-count) ;; update the binding to a hight value
arg))))) ;; and then the job, as example it's #'identity
call-count ; ==> ERROR call-count has not value
(my-func 'a) ; ==> a
(my-func 'b) ; ==> b
(my-func 'get) ; ==> 2
Upvotes: 2
Reputation: 60014
Try incf
for incrementing:
(defvar *call-count* 0)
(defun my-func (...)
(incf *call-count*)
...)
Read up on defvar
; it creates a dynamic variable but does not declare its type (use declaim
for that).
There is no int
in Lisp, just integer
, whose size is not limited by the standard (there is a smaller fixnum
size too, but there is no reason to declare this variable's type).
Upvotes: 3