代码之家  ›  专栏  ›  技术社区  ›  maxorcist

clojure:why(some#)(and…不返回第一个false项)

  •  1
  • maxorcist  · 技术社区  · 7 年前

    很抱歉提出这样一个基本的问题,但我不明白为什么这个函数可以工作。我正在做 "Clojure for the brave and true" 指南,并发生在这个集合:

    (def food-journal
      [{:month 1 :day 1 :human 5.3 :critter 2.3}
       {:month 1 :day 2 :human 5.1 :critter 2.0}
       {:month 2 :day 1 :human 4.9 :critter 2.1}
       {:month 2 :day 2 :human 5.0 :critter 2.5}
       {:month 3 :day 1 :human 4.2 :critter 3.3}
       {:month 3 :day 2 :human 4.0 :critter 3.8}
       {:month 4 :day 1 :human 3.7 :critter 3.9}
       {:month 4 :day 2 :human 3.7 :critter 3.6}])
    

    使用这个函数可以得到第一个有键的地图:值大于3的小动物。

     (some #(and (> (:critter %) 3) %) food-journal)
    

    我不明白的是 (and ) ,在我看来,它应该返回从内部表达式返回的第一个假值。也就是说,它应该返回自该地图之后的第一张地图:critter不大于3。

    2 回复  |  直到 7 年前
        1
  •  2
  •   MattBianco    7 年前

    some 评估食物日志中每个元素的谓词函数,直到谓词函数返回逻辑真值。

    每个项目(例如 {:month 1 :day 1 :human 5.3 :critter 2.3} )在收藏中恰巧对自己的真实评价。

    因此,谓词函数需要为集合中的所有项生成false,其中 :critter 不是 > 3 .

    and 当元素本身和:critter>3的计算结果为true。

    令人困惑的是,在这两者之间有一个逻辑和 元素本身 ,以及 大于比较中的布尔值 .

    所以,一个 or 取而代之的是始终为true,因此始终返回第一个元素,从而忽略大于测试。

        2
  •  2
  •   Taylor Wood    7 年前

    这里的关键是如何 some 正在使用谓词函数。

    对于coll中的任何x,返回(pred x)的第一个逻辑真值, 否则为零。

    那么什么时候 and 返回非true, 一些 只是一直在看。原因是 % 作为决赛 形式是这样的 一些 (> (:critter %) 3)