为什么Clojure中的这两个函数有不同的输出?

时间:2021-05-12 06:56:24

标签: clojure

为什么这两个函数的返回值不同?

(filter (and #(= (rem % 2) 1)
             #(= (rem % 3) 0)) 
          (take 100 (iterate inc 0)))  ;=> (0 3 6 9 12... 

(filter #(and (= (rem % 2) 1) 
              (= (rem % 3) 0)) 
          (take 100 (iterate inc 0)))  ;=> (3 9 15 21...

带有两个匿名函数的表单是否有效?

2 个答案:

答案 0 :(得分:3)

扩展另一个答案...

您无意中发现了 Clojure 的一个“特性”,恕我直言,它造成的麻烦比它的价值要大。

Clojure 中的“真实”是什么?

考虑一下 Clojure 认为什么是“真实的”:

(defn truthy?
  [x]
  (if x
    :yes
    :no))

(dotest
  (is= :yes (truthy? true))
  (is= :yes (truthy? 1))
  (is= :yes (truthy? :a))

  (is= :no (truthy? nil))
  (is= :no (truthy? false)))

请注意,函数对象也是“真实的”:

(dotest 
  (let [fn-obj-1 (fn [x] (+ x 1)) 
        fn-obj-2        #(+ % 1)]  ; shorthand, equiv to fn-obj-1
    (is= :yes (truthy? fn-obj-1))
    (is= :yes (truthy? fn-obj-2))
    (is= 42 (fn-obj-1 41))  ; call the fn
    (is= 42 (fn-obj-2 41))  ; call the fn
  ))

and 宏的“棘手”结果

and 宏 (source code) 并不像您期望的那样仅返回布尔值。相反,它返回“导致”结果的项目:

(dotest 
  (is= 3     (and 1 2 3))      ; 1
  (is= :a    (and 99 :a))      ; 2

  (is= nil   (and nil :a))     ; 3
  (is= false (and false 88)))  ; 4

因此,如果所有项目都是“真实的”,则 and 返回最后一个,因为它是“决定因素”(案例 1 和 2)。如果存在一个或多个“falsey”值,and 将返回找到的第一个值,因为它是“决定因素”(情况 3 和 4)。

就我个人而言,我从不使用 Clojure 的这个特性。恕我直言,这是一种使代码难以正确破译的“技巧”。

and 宏是如何工作的?

为了将“决定因素”返回给您,and 宏扩展为如下代码:

; (and 99 :a)
(let [x 99]
  (if x 
    ; recursive invocation: (and :a)
    x))

因此,如果 99 为 false 或 nil,则它会返回给您。由于 99 为真值,and 使用下一个值 :a 递归如下:

; (and :a)
:a

由于此递归级别中只有 1 个项目,因此它必须是“决定因素”,而 and 宏只是将原始值返回给您。

记住 and 是一个宏

这意味着它在编译时运行(每个宏都被正确地视为“编译器扩展”)。在您的第一种情况下,您的代码如下所示:

(filter (and f1 f2) ...)

其中 f1f2 都是函数。由于两者都是“真实的?”,and 将最后一项返回给您。由于使用 let 等重写上述代码是在编译时发生的,因此您的代码将转换为:

(filter 
  (let [x f1]
    (if x 
      f2
      f1))
  ...)

而且由于 f1 是真实的,所以简化为

(filter 
  f2
  ...)

其中 f2 就是 #(= (rem % 3) 0)。所以我们看到 [0 3 6 ...] 返回。


最终答案

由于 Clojure 的“怪癖”,您的第一个 filter 不会生成编译器错误(尽管我认为应该)。第二种形式可以满足您的需求,因为 filter 需要使用 1 个函数来决定保留哪些项目。


以上基于this template project

答案 1 :(得分:2)

表达式

(and #(= (rem % 2) 1) #(= (rem % 3) 0))

与仅编写以下内容相同:

#(= (rem % 3) 0))

这是因为 and 返回的第一个参数是 falsenil。如果没有,则返回最后一个参数。

如果要合并两个函数,可以使用every-pred

(every-pred #(= (rem % 2) 1) #(= (rem % 3) 0))