【问题标题】:Scala string.count('\t'==) Why does it work?Scala string.count('\t'==) 为什么有效?
【发布时间】:2015-06-16 14:32:29
【问题描述】:

假设我有一个字符串 s,如果我想计算字符串中制表符的数量,我可以执行以下操作:

string.count('\t'==) 

知道为什么会这样吗?我会期待一个谓词

参考:Count all occurrences of a char within a string

【问题讨论】:

  • '\t'== 等同于ch => '\t' == ch

标签: scala


【解决方案1】:

== 被用作“后缀运算符”,因此您实际上是将函数 '\t'.== 传递给 string.count

注意:如果我在 REPL 中打开 -feature 执行此操作,我会得到以下输出:

scala> "hello\tworld".count('\t'==)
<console>:8: warning: postfix operator == should be enabled
by making the implicit value language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scala docs for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
              "hello\tworld".count('\t'==)
                                       ^
> res0: Int = 1

添加点删除警告:

scala> "hello\tworld".count('\t'.==)
res1: Int = 1

【讨论】:

  • 但是尝试在 REPL 中输入'\t'.==。你说你正在传递一个函数,但混合中有重载和 eta 扩展。预期的类型至关重要。现在我必须赞成 b/c 赞成另一个答案。
【解决方案2】:

是你的问题

  • String 有没有函数count(p: (Char) ⇒ Boolean): Int
  • 一个 char 上的 == 方法是另一个 char 上的布尔函数吗?

答案:是的,是的。

【讨论】:

  • 多么棒的答案,但我明白他们为什么叫你Malvolio
【解决方案3】:

在 scala 中,您可以通过这种方式传递谓词:

def predicate(ch: Char) = { ... }

string.count(ch => predicate(ch))

或者这样

string.count(predicate(_))

还有一种方法可以省略参数占位符,看起来确实不错

string.count(predicate)

在您的示例中,您实际上是在调用 Char 的方法 '==',因此它与上面的代码非常相似。只是更不可读。

string.count('\t'.==) 

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 2023-03-28
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    相关资源
    最近更新 更多