2015-04-04 40 views
0

我遇到了一個名爲condp的Clojure中的函數,它採用二元謂詞,表達式和一組子句。每個子句可以採取either.Two實例的形式的它的用法是: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 

第一個例子是非常可以理解的,但功能的scond使用採用了特殊的語法中的:>>的形式,我沒有前面看過。任何人都可以解釋爲什麼這個關鍵字與condp函數一起使用,以及它是否在condp範圍之外使用。

回答

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)調用結果的函數,而不是要返回的值。