Reputation: 331
I have recently started to learn about Lisp, and I have this simple code which defines a function(using defun) and it creates an array of four elements and then it assigns the value 7 to the first position of the array
(defun func(setf array (make-array '(4))))
(setf (aref array 0) 7)
but it prints FUNC in the output, why is that??
Upvotes: 2
Views: 534
Reputation: 51501
A function always needs a parameter list, even if it is empty
(defun func () ; <- here
(setf array (make-array '(4)))
(setf (aref array 0) 7))
Evaluating this form defines and registers the function named func
and returns the symbol it is registered with. That's why you see FUNC
then, and it is quite right and expected.
There are other problems:
When you do (setf array...)
here, array
is not defined. In principle, anything could happen, but in practice, a global variable will be created and set which might or might not be declaimed special
(i. e. of dynamic extent).
You should create a local variable instead. This is usually done using let
:
(defun func ()
(let ((array (make-array '(4))))
(setf (aref array 0) 7)))
This does not do much, since the return value is the last value assigned by setf
, which is 7
. You would most likely want to return the array:
(defun func ()
(let ((array (make-array '(4))))
(setf (aref array 0) 7))
array))
Note that elements 1, 2, and 3 are not initialized, so trying to read from them has undefined behaviour later (unless you set their values before, of course). If you want to treat the array as being filled only to the first element, you could use a fill-pointer
:
(defun func ()
(let ((array (make-array 4 :fill-pointer 0)))
(vector-push 7 array)
array))
If you just need the exact structure of your array
, you could copy a literal:
(defun func ()
(copy-seq #(7 0 0 0)))
Upvotes: 3