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

查看:133
本文介绍了为什么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表示无或

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.

懒惰 - 为了确保容易的JVM互操作性,Clojure使用nil是有意义的。这里的逻辑是相当复杂,但我的理解是,使用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.

虚假 - 使用nil表示无很方便,条件代码来检查集合 - 所以你可以编写代码(if(some-map:some-key)....)来测试一个hashmap是否包含一个值给定的键。

"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中还有一些函数返回一个空列表。一个例子是rest:

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天全站免登陆