代码之家  ›  专栏  ›  技术社区  ›  Greg Rogers

如何获得Clojure中两个整数之间的排序集中的数字序列?

  •  6
  • Greg Rogers  · 技术社区  · 15 年前

    假设我有一组经过排序的整数,xs,我想检索xs中所有[x,y]的整数,即x和y之间的整数。

    我能做到:

    (select #(and (>= % x) (< % y)) xs)
    

    但这是低效的—当它可以是O(log n)时,我希望返回的元素数量很小。使用take while和drop while可以让我在到达y之后退出,但我仍然不能有效地跳到x。

    我只是学习Culjule,所以这里是我将如何在C++中完成:

    set<int>::iterator first = xs.lower_bound(x);
    set<int>::iterator last = xs.lower_bound(y);
    for (; first != last; ++first)
        // do something with *first
    

    我可以在Clojure做这个吗?

    1 回复  |  直到 13 年前
        1
  •  8
  •   mikera    13 年前

    哎呀!我错过了 subseq 函数,文档的数据结构页没有指向它的链接。

    (subseq xs >= x < y)
    
    推荐文章