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

最后都变了- 提交于 2020-01-03 17:47:49

问题


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.



来源:https://stackoverflow.com/questions/49370733/boolean-values-t-vs-nil-vs-1-vs-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!