Clojure 相当于 Python 的“any”和“全部”功能?
Clojure 中是否有类似于 Python 的 any
和 all
函数的内置函数?
例如,在 Python 中,它是 all([True, 1, 'non-empty string']) == True
。
Are there built in functions in Clojure similar to Python's any
and all
functions?
For example, in Python, it's all([True, 1, 'non-empty string']) == True
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(每个?f数据)
[文档]< /sup> 与all(f(x) for x in data)
相同。(一些f数据)
[docs] 与any(f(x) for x in data)
类似,只是它返回f(x)
的值(必须为真值),而不仅仅是真
。如果您想要与 Python 中完全相同的行为,可以使用
identity
函数,该函数将仅返回其参数(相当于(fn [x] x)
)。(every? f data)
[docs] is the same asall(f(x) for x in data)
.(some f data)
[docs] is likeany(f(x) for x in data)
except that it returns the value off(x)
(which must be truthy), instead of justtrue
.If you want the exact same behaviour as in Python, you can use the
identity
function, which will just return its argument (equivalent to(fn [x] x)
).在 clojure 中,
and
和or
与 python 的all
和any
非常相似,但需要注意的是(就像 < code>clojure.core/some)它们返回满足它的元素...因此您可以将它与boolean
一起使用来转换它我使用
boolean
> 而不是true?
因为后者将返回true
iff 参数的值是 true...所以boolean
更类似于 python 的bool
因为它评估真实性与
some
& 不同每个?
、和
&or
是宏,因此如果您总是想将结果转换为布尔值,则不能简单地执行(def any (comp boolean or))
,而是必须定义一个宏就像宏的副作用/优点一样,是它们是惰性的/可以短路(就像 python 的
and
和or
一样,它们是中缀二元运算符)他们就像python 的
any
和all
,即使在 python 中不带参数调用时:
如果您更喜欢调用
any
/all
使用单个列表/序列参数,您可以简单地执行以下操作:In clojure
and
andor
are quite similar to python'sall
andany
, with the caveat that (just likeclojure.core/some
) they return the element that will satifsy it... thus you can use it together withboolean
to convert itI use
boolean
instead oftrue?
since the latter will returntrue
iff the argument is the value true... soboolean
is more akin to python'sbool
in that it evaluates the truthynessUnlike
some
&every?
,and
&or
are macros, so if you always want to convert the result to a boolean, you cannot simply do(def any (comp boolean or))
but you have to define a macro likea side-effect/advantage of being macros, is that they are lazy/can shortcircuit (just like python's
and
&or
, that are infix binary operators however)and they're just like python's
any
andall
, even when called without argumentsin python:
If you prefer to have to call
any
/all
with a single list/sequence argument, you can simply do: