检查参数是列表还是原子
如何检查某物是否是原子?我正在寻找类似 number?
或 list?
的内容。
How do I check if something is an atom? I'm looking for something like number?
or list?
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您也想排除空列表:
或者,如果您想更加迂腐,那么也禁止向量:
当然您可以在此处添加更多内容 - 因为它被标记为球拍问题,您可能想要添加哈希表、结构体等。因此,指定您视为原子的值的种类也可以更容易:
或使用球拍合约系统:
Usually, you'll want to exclude the empty list too:
or, if you want to be more pedantic, then forbid vectors too:
And of course you can add much more here -- since it's marked as a racket question, you might want to add hash tables, structs, etc etc. So it can just as well be easier to specify the kinds of values that you do consider as atoms:
or using the racket contract system:
当各种方案不包含它时,我经常看到
atom?
是这样定义的:如果
x
不是一对(或列表),则返回 true。它将为数字、字符串、字符和符号返回 true,而symbol?
自然只会为符号返回 true。这可能是也可能不是您想要的。比较 Yasir Arsanukaev 的示例:它使用
pair?
因为这会检查(1 2 3)
等正确列表,以及(a . b)
等对,而list?
对于点对和点尾列表将返回 false。When various Schemes don't include it, I've often seen
atom?
defined this way:This will return true if
x
is not a pair (or a list). It will return true for numbers, strings, characters, and symbols, whilesymbol?
will only return true for symbols, naturally. This might or might not be what you want. Compare Yasir Arsanukaev's example:It uses
pair?
because this checks for proper lists like(1 2 3)
, pairs like(a . b)
, whilelist?
will return false for dotted pairs and dotted-tail lists.