简体   繁体   English

如何从Clojure中的first获取默认值?

[英]How do I get a default value from first in Clojure?

(> 1 (first [])) returns NullPointerException. (> 1 (first []))返回NullPointerException。

How can I make (first []) return a default value, such as 0, instead of nil? 如何使(first [])返回默认值,例如0,而不是nil?

You can use or to bypass the nil value 您可以使用or绕过nil

(> 1 (or (first []) 0))

Because in Clojure, nil is treated as a falsy value. 因为在Clojure中, nil被视为虚假值。

The or solution is good for this case. or解决方案适用于这种情况。 For cases where or is not sufficient, another option is to use the with-exception-default macro from the Tupelo library : 对于其中的情况下or是不够的,另一种选择是使用with-exception-default的宏从图珀洛库

(with-exception-default default-val & body)
 "Evaluates body & returns its result.  In the event of an exception the
  specified default value is returned instead of the exception."

(with-exception-default 0
  (Long/parseLong "12xy3"))
;=> 0

Use fnil : 使用fnil

A function that replaces a nil second argument to > with 0 is ... 用0替换>第二个nil参数的函数是...

(fnil > nil 0)

So that, for instance, 例如,

((fnil > nil 0) 1 (first []))
=> true

imho you should clearly define the functional objects in your design 恕我直言,您应该清楚地定义设计中的功能对象

since you need a functionality: given a collection coll extract the first element or default to 0 then you should have a separate function for that. 因为您需要功能:给定集合coll提取第一个元素或默认为0,那么您应该为此使用一个单独的函数。

eg 例如

(defn first-or-zero [coll] 
 (if (seq coll)
   (first coll) 0))

Although a bit cumbersome to write (and the or macro does seem to get you there quicker you are missing out on the powerful concept that is FP. 尽管编写起来有点麻烦(并且or宏的确使您更快地到达了那儿,但您却错过了功能强大的FP概念。

a) doing this way you have a pure functional description of what you need to do b) you can test it either by proof or by unit-testing c) you can reuse it all over the place with minimum impact on change a)这样,您对需要做的事情有纯粹的功能描述b)您可以通过证明或通过单元测试来对其进行测试c)您可以在所有地方重复使用它,而对更改的影响最小

A more FP way of doing it would be: FP的一种更有效的实现方式是:

(defn first-or-default 
  ([coll] (first-or-default coll 0))
  ([coll dflt-val] 
   (if (seq coll)
      (first coll) dflt-val)))

Then just call: (< 1 (first-or-default coll 0)) 然后只需调用: (< 1 (first-or-default coll 0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM