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))
?
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"
If you know that it's a list, you can use (pair? x)
, since every list is either a pair or '()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With