【问题标题】:std.algorithm.filter!() template with two parameters instead of just one?std.algorithm.filter!() 模板有两个参数而不是一个?
【发布时间】:2011-04-21 08:09:18
【问题描述】:

这是一个例子:

int[] arr = [ 1, 2, 3, 4, 5 ];
auto foo = filter!("a < 3")(arr);
assert(foo == [ 1, 2 ]); // works fine

现在我希望能够参数化谓词,例如

int max = 3;
int[] arr = [ 1, 2, 3, 4, 5 ];
auto foo = filter!("a < max")(arr); // doesn't compile

这个 sn-p 显然不会编译,正弦过滤器!()的谓词只接受一个参数。有没有办法克服这个限制而不求助于好的 ol' for/foreach 循环?

【问题讨论】:

    标签: d dmd


    【解决方案1】:

    字符串 lambda 只是库级别的便利,旨在比 D 的内置函数/委托/模板文字更简洁。当您需要更多电源时,请执行以下操作:

    注意:以下应该可以工作,但由于编译器错误,在撰写本文时可能会出现异常。

    import std.algorithm;
    
    void main() {
        int max = 3;
        int[] arr = [ 1, 2, 3, 4, 5 ];
        auto foo = filter!((a) { return a < max; })(arr);
    }
    

    以下确实有效:

    import std.algorithm;
    
    void main() {
        int max = 3;
        int[] arr = [ 1, 2, 3, 4, 5 ];
        auto foo = filter!((int a) { return a < max; })(arr); 
    }
    

    区别在于是否明确指定了类型。

    【讨论】:

    • 我会编辑您的帖子,但仍在为代表工作。您应该修改第二个示例的注释。
    • @he_the_great:实际上两者都可以编译。该评论来自我从 OP 复制/粘贴并忘记删除该评论。不过现在已修复。
    【解决方案2】:

    除了dsimcha的回答,如果你喜欢,你也可以使用本地函数:

    int max = 3;
    bool pred(int a) { return a < max; };
    int[] arr = [1, 2, 3, 4, 5];
    auto foo = filter!(pred)(arr);
    

    【讨论】:

      猜你喜欢
      • 2010-12-01
      • 2017-05-10
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 2011-12-26
      • 1970-01-01
      相关资源
      最近更新 更多