为什么 Clojure 习语更喜欢返回 nil 而不是像 Scheme 那样的空列表? [英] Why Clojure idiom prefer to return nil instead of empty list like Scheme?

查看:17
本文介绍了为什么 Clojure 习语更喜欢返回 nil 而不是像 Scheme 那样的空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自对另一个问题的评论,有人说 Clojure 习惯用法更喜欢返回 nil 而不是像 Scheme 中的空列表.这是为什么?

From a comment on another question, someone is saying that Clojure idiom prefers to return nil rather than an empty list like in Scheme. Why is that?

喜欢

(when (seq lat) ...)

代替

  (if (empty? lat)  
    '() ...)

推荐答案

我能想到几个原因:

  • 逻辑区别.在 Clojure 中,nil 意味着没有/没有价值.而 '() "空列表一个值 - 它恰好是一个空列表的值.通常在概念和逻辑上区分两者是有用的.

  • Logical distinction. In Clojure nil means nothing / absence of value. Whereas '() "the empty list is a value - it just happens to be a value that is an empty list. It's quite often conceptually and logically useful to distinguish between the two.

适合 JVM - JVM 对象模型支持空引用.并且相当多的 Java API 返回 null 表示没有"或未找到值".因此,为了确保简单的 JVM 互操作性,Clojure 以类似的方式使用 nil 是有意义的.

Fit with JVM - the JVM object model supports null references. And quite a lot of Java APIs return null to mean "nothing" or "value not found". So to ensure easy JVM interoperability, it makes sense for Clojure to use nil in a similar way.

懒惰 - 这里的逻辑相当复杂,但我的理解是,使用 nil 表示无列表"更适合 Clojure 的 惰性序列.由于默认情况下 Clojure 是一种惰性函数式编程语言,因此将这种用法标准化是有意义的.请参阅 http://clojure.org/lazy 以获得一些额外的解释.

Laziness - the logic here is quite complicated, but my understanding is that using nil for "no list" works better with Clojure's lazy sequences. As Clojure is a lazy functional programming language by default, it makes sense for this usage to be standard. See http://clojure.org/lazy for some extra explanation.

Falsiness" - 在编写检查集合的条件代码时,使用 nil 表示无"和假"很方便 - 因此您可以编写类似 (if (some-map :some-key) ....) 测试哈希图是否包含给定键的值.

"Falsiness" - It's convenient to use nil to mean "nothing" and also to mean "false" when writing conditional code that examines collections - so you can write code like (if (some-map :some-key) ....) to test if a hashmap contains a value for a given key.

性能 - 测试 nil 比检查列表是否为空更有效......因此,采用此习语作为标准可以导致更高性能的习语代码

Performance - It's more efficient to test for nil than to examine a list to see if it empty... hence adopting this idiom as standard can lead to higher performance idiomatic code

请注意,Clojure 中仍有一些函数会返回空列表.一个例子是休息:

Note that there are still some functions in Clojure that do return an empty list. An example is rest:

(rest [1])
=> ()

这个关于休息与下一步的问题详细说明了为什么这是.....

This question on rest vs. next goes into some detail of why this is.....

这篇关于为什么 Clojure 习语更喜欢返回 nil 而不是像 Scheme 那样的空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆