Lisp, add a new list in db to the "for" loop, why return NIL?

I wonder how I can print in LISP every new value from the "for" loop in a new list, which it creates each time by calling a function.

I created func:

(defun make (id name surname) (list :id id :name name :surname surname) ) 

Here I created a global variable:

 (defvar *db* nil) 

And here I defined func to add each new value to save it in db:

 (defun add (cd) (push cd *db*)) 

So, I can add all the new data in db, for example:

 (add (make 0 "Oleg" "Orlov" ) ) 

To see the contents of my db, I can use:

 *db* 

So, I am wondering how to put each new list of records in db using the "for" loop, I print the values ​​in the "for" loop in LISP as follows:

  (loop for i from 1 to 10 do ( ... )) 

If, I use:

  (loop for i from 0 to 10 do (add (make i "Oleg" "Orlov") ) ) 

If you read db using *db* , you will see that all evelen entries have been added, but after calling the last line you will get a NIL result in response.

Why do I catch the result of NIL, not T, and what does it mean?

Thanks, Regards!

+4
source share
1 answer

Each form in Lisp appreciates something.

If the form you enter does not return a value, it will evaluate to NIL by default (otherwise, it will evaluate the return values). Your loop does not actually return the value itself; it simply performs 10 assignments (each of the intermediate expressions returns a value, but you do not collect or return them). Therefore, this code will return NIL .

If you haven’t already done so, check out Chapter 3 of Practical General Lisp , in which Peter Seibel goes step by step through the process of creating a simple database. This may give you some insight into how Lisp works. The specific question you ask (why forms return NIL by default, and what exactly means in the context of Common Lisp), will be answered in chapter 2 by the same book

Regarding how you explicitly invoke your loop emit a list of elements added to *db* , try the following

 (loop for i from 1 to 10 for elem = (make i "Oleg" "Orlov") do (add elem) collect elem) 
+5
source

Source: https://habr.com/ru/post/1392258/


All Articles