【问题标题】:Why Can't I Use std.algorithm.count With a Predicate Function为什么我不能将 std.algorithm.count 与谓词函数一起使用
【发布时间】:2015-10-09 20:22:00
【问题描述】:

以下代码编译失败:

assert("(((())))()()()()))".count!(c => c.among!('(', ')')) > 0);

带有错误信息:

"Error: template std.algorithm.searching.count cannot deduce function from argument types !((c) => c.among!('(', ')'))(string), candidates are..."

但是 [标准库 (http://dlang.org/phobos/std_algorithm_searching.html#.count) 清楚地表明存在count 的重载,它采用谓词,计算谓词返回 true 的 R 的所有元素。那么,当我尝试以这种方式使用count 时,为什么编译器会报错呢?

【问题讨论】:

    标签: d phobos


    【解决方案1】:

    assert("(((())))()()()()))".count!(c => c.among!('(', ')') != 0) > 0);

    问题是:

    1. 您的 lambda 返回 uint 而不是 bool(查看文档以了解 among 的返回值)。
    2. 编译器错误没有帮助。

    【讨论】:

    • 这很奇怪,模板约束明确表示is(typeof(unaryFun!pred(haystack.front)) : bool)。我原以为 is(uint: bool) 会返回 true,但我想不会。
    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2013-07-02
    • 2015-11-08
    相关资源
    最近更新 更多