condp及其冒号双V形句法

时间:2015-04-04 20:32:48

标签: clojure

我在Clojure中遇到了一个名为condp的函数,它接受一个二元谓词,一个表达式和一组子句。每个子句都可以采用任何一种形式。它的两个例子是:

(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范围之外使用。

1 个答案:

答案 0 :(得分:1)

让我们看看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)调用的结果上调用的函数,而不是要返回的值。 / p>