简体   繁体   English

以下clojure代码如何运行?

[英]How does the following clojure code run?

I read the doc about condp from clojuredoc. 我从clojuredoc上读到了关于condp的文档。 And in the doc I found the following code: 在文档中我找到了以下代码:

(condp some [1 2 3 4] #{0 6 7} :>> inc #{4 5 9} :>> dec #{1 2 3} :>> #(+ % 3))

The result of the above code is 3. But I don't understand why. 上面代码的结果是3.但我不明白为什么。

If someone could help me figure it out ? 如果有人可以帮助我解决这个问题? Tell me how does the code run. 告诉我代码是如何运行的。

Thank you~ 谢谢〜

Sure let's start with a simpler case: 当然,让我们从一个更简单的案例开始:

user> (condp some [1 2 3 4] 
             #{5}  :>> inc 
             :the-default-value)

:the-default-value

Builds this test: 构建此测试:

user> (some #{5} [1 2 3 4])
nil

Because the test returns something falsy (nil is falsy) it skips this clause and returns the default value at the end because there are no more clauses to check. 因为测试返回了一些假的(nil是假的)它跳过这个子句并在结尾返回默认值,因为没有更多的子句要检查。

If we use a test that passes 如果我们使用通过的测试

user> (condp some [1 2 3 4] #{1}  :>> inc :the-default-value)
2

It builds the test: 它构建了测试:

user> (some #{1} [1 2 3 4])
1

Which results in something truthy (1) so the search stops and this clause is accepted. 这导致了一些真实的东西(1)因此搜索停止并且该子句被接受。 The :>> tells condp to take the result of the test and pass it to the function that follows , in this case inc . :>>告诉condp获取测试结果并将其传递给后面的函数 ,在本例中为inc Resulting in 2 结果2

So in the original example the first test is: 所以在最初的例子中,第一个测试是:

(some #{0 6 7} [1 2 3 4]) 

Which is nil so this case is not accepted and the search continues. 哪个是nil所以不接受这个案例并继续搜索。 The second test is: 第二个测试是:

user> (some #{4 5 9} [1 2 3 4])
4

Which results in the truthy value 4, so it calls the provided function dec on the value 4: 这导致truthy值为4,因此它在值4上调用提供的函数dec

user> (dec 4) 
3

and the search stops. 并且搜索停止。

In this example, condp tries the predicate some on each test expression in turn, with [1 2 3 4] as the second argument. 在这个例子中, condp尝试谓词some上依次在每个测试表达式,与[1 2 3 4]作为第二个参数。

  • (some #{0 6 7} [1 2 3 4]) fails, returning nil . (some #{0 6 7} [1 2 3 4])失败,返回nil
  • (some #{4 5 9} [1 2 3 4]) succeeds, returning 4 . (some #{4 5 9} [1 2 3 4])成功,返回4

condp then returns the result of applying the function corresponding to the succeeding test expression, in this case dec , to the test value 4 . condp然后返回将对应于后续测试表达式的函数(在这种情况下为dec )应用于测试值4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM