我在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
第一个例子是可以理解的,但是函数的scond用法使用了一种特殊的:>>
语法,这是我以前从未见过的。有谁能解释为什么在condp
函数中使用这个关键字,以及它是否在condp
范围之外使用。
发布于 2015-04-04 21:03:43
让我们来看看文档
=> (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
宏中用作某种句法糖的一个普通关键字。
=> (class :>>)
clojure.lang.Keyword
=> (name :>>)
">>"
:>>
关键字在condp
宏中使用,以指示以下内容是要在(pred test-expr expr)
调用结果中调用的函数,而不是要返回的值。
https://stackoverflow.com/questions/29451115
复制相似问题