Reputation: 1091
I have come across a function in Clojure named condp
which takes a binary predicate, an expression, and a set of clauses. Each clause can take the form of either.Two examples of it's usage are:
(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
The first example is very understandable, but the scond usage of the function uses a special syntax in the form of :>>
which I have not seen before. Can anybody explain why this keywords is used with the condp
function and whether it has uses outside the scope of condp
.
Upvotes: 1
Views: 795
Reputation: 51480
Let's have a look at 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.
So, :>>
is just an ordinary keyword used in condp
macro as some kind of syntactic sugar:
=> (class :>>)
clojure.lang.Keyword
=> (name :>>)
">>"
:>>
keyword is used in condp
macro to indicate that the following thing is a function to be called on the result of (pred test-expr expr)
call, rather than the value to be returned.
Upvotes: 3