Lisp if not nil

30,687

Since nil is equivalent to the boolean value false, there is no need to compare to it explicitly.

A simple

(if testvar
  (...)
  (...))

will do the job. You only need not if you want to check for the opposite, e.g. if you want to check that a variable is not nil:

(if (not testvar)
  (...)
  (...))

Apart from that, there is also a predicate function called null that you might use. It is basically meant for checking whether a given list is empty, but since the empty list is equivalent to nil, it will work (as the examples on the linked page point out):

(null '()) =>  T
(null nil) =>  T
(null t) =>  NIL
(null 1) =>  NIL

Anyway, this basically only moves the problem one layer up ;-)

Share:
30,687
JT93
Author by

JT93

Updated on July 09, 2022

Comments

  • JT93
    JT93 almost 2 years

    I am so sorry for having to ask this question but I'm trying to do a simple if statement that checks if a variable is nil or not.

    (defun test (input)
      (let ((testvar (first input)))
       (if (not nil testvar)
        (do this)
        (do that))))
    

    Could anyone explain the proper syntax to me?

  • Joshua Taylor
    Joshua Taylor about 8 years
    A stylistic comment: If testvar is "intended" to be a boolean, then (if testvar ...) and (if (not testvar) ...) are the way to go, in my opinion. If testvar is some other kind of value that might just happen to be nil, then you might use (if (not (null testvar)) ...) and (if (null testvar) ..). The compiler should probably optimize them to be the same, but it may make the code easier to read for someone else.