(> 1 (first []))
返回NullPointerException。
如何让(first [])
返回默认值,例如0,而不是nil?
答案 0 :(得分:3)
您可以使用or
绕过nil
值
(> 1 (or (first []) 0))
因为在Clojure中,nil
被视为假值。
答案 1 :(得分:2)
or
解决方案适合这种情况。对于or
不足的情况,另一种选择是使用with-exception-default
宏from the Tupelo library:
(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
答案 2 :(得分:1)
答案 3 :(得分:0)
因为你需要一个功能:给定一个集合coll提取第一个元素或者默认为0,那么你应该有一个单独的函数。
e.g。
(defn first-or-zero [coll]
(if (seq coll)
(first coll) 0))
虽然编写起来有点麻烦(or
宏似乎确实让你更快,但你错过了强大的FP概念。
a)通过这种方式,您可以对您需要做的事情进行纯粹的功能描述 b)您可以通过证明或单元测试来测试它 c)您可以在整个地方重复使用它,对变化的影响最小
更多的FP方式是:
(defn first-or-default
([coll] (first-or-default coll 0))
([coll dflt-val]
(if (seq coll)
(first coll) dflt-val)))
然后只需致电:(< 1 (first-or-default coll 0))