Best way to check if a list is null?

In Common Lisp, if I wanted to check if the list was not null, I could just use this list as a condition, since all non-nil lists are considered true. However, I find that in Scheme, having done the same, Scheme will think that I am trying to call a function. Is there a better way to check if a list is null in a Schema than to define another function that does (not (null? x)) ?

+6
source share
2 answers

In the scheme, everything that is not #f is true, therefore '() is considered #t in if .

Thus,

 (if '() "true" "false") => "true" (not '()) => #f 

Using (not (null? x)) is the easiest way to check if a list is not null: it describes exactly what you want, and in the case of corners where you are given what is not a list, it will give you something else behavior:

 (if (not (null? #t)) "true" "false") => "true" (if (not #t) "true" "false") => "false" 
+7
source

If you know this is a list, you can use (pair? x) , since each list is either a pair or '() .

+4
source

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


All Articles