什么是正确的“clojure方式”以检查集合是否为非空 [英] What is the correct "clojure way" to check if a collection is non empty

查看:100
本文介绍了什么是正确的“clojure方式”以检查集合是否为非空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数,如果给定的集合不为空则返回boolean true,否则返回false。



我可以做

  defn .. 
(boolean(seq coll))

  defn .. 
))



由于我是clojure的新人,我最初倾向于使用#2 ,但clojure api引用 empty?明确说使用惯例(seq coll)而不是(not(empty?coll)),也许可以避免双重否定。



我想知道什么是clojure方法检查如果一个集合是非空的并返回一个布尔值true / false。

解决方案

? c>你提到的docstring意味着特别是这样的非空?函数永远不需要,甚至是特别有用,因为 seq 可以始终在布尔上下文中使用,在纯Clojure代码中可以。



如果你觉得被迫写这样的功能,我会说,我喜欢第一种方法更好。 空?建立在 seq ,所以没有避免调用它;只是将结果转换为布尔值比通过而不是的两个行程更清晰。对于其他选项, nil? false?(我还是喜欢演员)。


$ b顺便说一下,你为什么要写这个...?对于调用具有 boolean 参数的Java方法?



更新:一个例子来说明后一点:


  1. 一个简单的Java类:

      public class Foo {
    public static boolean foo(boolean arg){
    return!arg;
    }
    }


  2. 一些Clojure客户端代码:

     (Foo / foo nil)
    ; => NullPointerException
    (Foo / foo(boolean nil))
    ; => true



I want to write a function that would return the boolean true if the given collection is not empty and false otherwise.

I could either do

defn ..
(boolean (seq coll))

or

defn ..
(not (empty? coll))

As I am new to clojure I was initially inclined to go with #2 (more readable), but the clojure api reference for empty? explicitly says use the idiom (seq coll) instead of (not (empty? coll)), maybe to avoid double negation.

I want to know what is the clojure way to check if a collection is non-empty and return a boolean true/false.

解决方案

The passage from empty?'s docstring which you mentioned means in particular that such a nonempty? function should never be necessary, or even particularly useful, because seq can always stand in for it in Boolean contexts, which in pure Clojure code it can.

If you feel compelled to write such a function nonetheless, I'll say that I like the first approach better. empty? is built on seq anyway, so there's no avoiding calling it; just casting the result to Boolean seems cleaner than two trips through not. For other options, see e.g. nil?, false? (I still prefer the cast).

Incidentally, why do you want to write this...? For calling a Java method with a boolean argument perhaps? In that case, I think the cast would express the intention nicely.

Update: An example to illustrate the latter point:

  1. A simple Java class:

    public class Foo {
      public static boolean foo(boolean arg) {
        return !arg;
      }
    }
    

  2. Some Clojure client code:

    (Foo/foo nil)
    ; => NullPointerException
    (Foo/foo (boolean nil))
    ; => true
    

这篇关于什么是正确的“clojure方式”以检查集合是否为非空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆