Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if a list is not null?

Tags:

scheme

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

like image 469
wrongusername Avatar asked Sep 09 '11 10:09

wrongusername


2 Answers

In Scheme, everything that's not #f is truthy, so '() is considered #t in if statements.

Thus,

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

Using (not (null? x)) is the most straightforward way of checking if a list is not null: it describes exactly what you want, and in corner cases where you're given something that's not a list, it will give you different behavior:

(if (not (null? #t)) "true" "false") => "true"
(if (not #t) "true" "false") => "false"
like image 175
erjiang Avatar answered Nov 03 '22 03:11

erjiang


If you know that it's a list, you can use (pair? x), since every list is either a pair or '().

like image 24
Sam Tobin-Hochstadt Avatar answered Nov 03 '22 04:11

Sam Tobin-Hochstadt