Boolean values: t vs. nil vs 1 vs -1

2019-06-25 14:01发布

问题:

In Elisp, I've encountered different APIs for modeling boolean values.

I was under the impression that t and nil were the idiomatic ways of representing true and false respectively. However, I've also seen 1 and -1 used to model the same thing.

What confuses me is that I have come across APIs that won't work if nil is supplied but will work if -1 is used.

Can someone help me understand which is in fact the preferred way. And if the answer is t and nil, I welcome any theories on why some developers use 1 and -1 for their APIs...

回答1:

sds and sepp2k have covered the main misconception, but in answer to:

why some developers use 1 and -1 for their APIs...

The reason that Emacs minor modes use positive and negative numbers (or rather non-positive numbers, including zero) to mean "enable" and "disable", rather than using t and nil, is that the argument is optional, and when an optional argument is not supplied its value will be nil. Consequently it would not be possible to distinguish between passing an argument of nil explicitly, and not passing an argument at all.

Historically, passing no argument (i.e. an argument of nil) meant that the mode would be toggled.

These days the mode is only toggled when calling it interactively, and an argument of nil means "enable". This change was made so that the likes of (add-hook 'prog-mode-hook 'some-minor-mode) -- which will result in some-minor-mode being called with no arguments -- is guaranteed to enable that mode.



回答2:

Lisp

In lisp (both Emacs Lisp and Common Lisp) the only false value is nil. Everything else is true, including 0, -1 &c &c.

Emacs

Emacs uses negative arguments (including -1) to indicate "turn off this mode". E.g., C-h f toggle-truncate-lines

With prefix argument ARG, truncate long lines if ARG is positive, otherwise fold them.



标签: lisp elisp