condp 及其冒号双人字形语法

condp and its colon double chevron syntax

我在 Clojure 中遇到一个名为 condp 的函数,它接受一个二元谓词、一个表达式和一组子句。每个子句都可以采用 either.Two 的形式,其用法示例如下:

(defn foo [x]
  (condp = x
    0 "it's 0"
    1 "it's 1"
    2 "it's 2"
    (str "else it's " x))) 

(foo 0) => "it's 0"

(defn baz [x]
  (condp get x {:a 2 :b 3} :>> (partial + 3)
               {:c 4 :d 5} :>> (partial + 5)
               -1))
(baz :b) => 6

第一个例子很好理解,但是函数的第二个用法使用了一种特殊的语法,形式为:>>,这是我以前从未见过的。谁能解释为什么这个关键字与 condp 函数一起使用,以及它是否在 condp.

范围之外使用

我们来看看condp documentation:

=> (doc condp) ; in my REPL
-------------------------
clojure.core/condp
([pred expr & clauses])
Macro
  Takes a binary predicate, an expression, and a set of clauses.
  Each clause can take the form of either:

  test-expr result-expr

  test-expr :>> result-fn

  Note :>> is an ordinary keyword.

  For each clause, (pred test-expr expr) is evaluated. If it returns
  logical true, the clause is a match. If a binary clause matches, the
  result-expr is returned, if a ternary clause matches, its result-fn,
  which must be a unary function, is called with the result of the
  predicate as its argument, the result of that call being the return
  value of condp. A single default expression can follow the clauses,
  and its value will be returned if no clause matches. If no default
  expression is provided and no clause matches, an
  IllegalArgumentException is thrown.

因此,:>> 只是 condp 宏中用作某种 syntactic sugar:

的普通关键字
=> (class :>>)
clojure.lang.Keyword
=> (name :>>)
">>"

:>>关键字用在condp宏中表示下面的东西是在(pred test-expr expr)调用的结果上调用的函数,而不是要返回的值.