简体   繁体   English

高阶函数和简短形式

[英]Higher-order functions and short forms

Why we can write 为什么我们可以写

 (defn factory-foo [] (fn [] (println "foo")))
 (apply (factory-foo) [])

but not: 但不是:

 (defn factory-bar [] #((println "bar")))
 (apply (factory-bar ) []) ;throws NPE

Is this a bug? 这是错误吗?

#((println "bar)) is translated by the reader to (fn [] ((println "bar"))) - note the extra parentheses. (println "bar") here prints bar and returns nil , and then nil itself is called as a function because of the outer parentheses. nil is null in fact, and an attempt to dereference it results to NPE. #((println "bar))被读者翻译为(fn [] ((println "bar"))) -注意多余的括号。 (println "bar")在这里打印bar并返回nil ,然后返回nil本身由于外部括号而称为“函数”,而nil实际上为null ,因此尝试将其取消引用为NPE。

To avoid this just drop extra pair of parentheses inside #(..) : #(println "bar") . 为了避免这种情况,只需在#(..)内放入多余的一对括号: #(println "bar")

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

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