Clojure 中 IFn 和 Fn 的区别

Differences between IFn and Fn in Clojure

我无法理解 IFn 和 fn 之间的区别。

你也能举个例子吗?

请提供这些函数之间的区别:

(fn? x)

(ifn? x)

他们的行为是一样的。

Clojure 文档非常清楚地描述了差异:

(fn? x) Returns true if x implements Fn, i.e. is an object created via fn.

(ifn? x) Returns true if x implements IFn. Note that many data structures (e.g. sets and maps) implement IFn

你可以测试一下:

(fn? (fn [] nil)) ;; => true
(fn? #{}) ;; => false
(fn? {}) ;; => false
(fn? []) ;; => false
(fn? :a) ;; => false
(fn? 'a) ;; => false

(ifn? (fn [] nil)) ;; => true
(ifn? #{}) ;; => true
(ifn? {}) ;; => true
(ifn? []) ;; => true
(ifn? :a) ;; => true
(ifn? 'a) ;; => true

换句话说,fn? 说如果它的参数是一个对象,它只是一个函数(用 (fn ...) 创建),ifn? 说如果一个对象是一个东西可以像函数一样调用(即使它不是用 (fn ...) 创建的)。