首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >condp及其冒号双chevron语法

condp及其冒号双chevron语法
EN

Stack Overflow用户
提问于 2015-04-04 20:32:48
回答 1查看 596关注 0票数 1

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

代码语言:javascript
运行
复制
(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范围之外使用。

EN

Stack Overflow用户

回答已采纳

发布于 2015-04-04 21:03:43

让我们来看看文档

代码语言:javascript
运行
复制
=> (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宏中用作某种句法糖的一个普通关键字。

代码语言:javascript
运行
复制
=> (class :>>)
clojure.lang.Keyword
=> (name :>>)
">>"

:>>关键字在condp宏中使用,以指示以下内容是要在(pred test-expr expr)调用结果中调用的函数,而不是要返回的值。

票数 3
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29451115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档