【发布时间】:2015-06-16 14:32:29
【问题描述】:
假设我有一个字符串 s,如果我想计算字符串中制表符的数量,我可以执行以下操作:
string.count('\t'==)
知道为什么会这样吗?我会期待一个谓词
【问题讨论】:
-
'\t'==等同于ch => '\t' == ch
标签: scala
假设我有一个字符串 s,如果我想计算字符串中制表符的数量,我可以执行以下操作:
string.count('\t'==)
知道为什么会这样吗?我会期待一个谓词
【问题讨论】:
'\t'== 等同于ch => '\t' == ch
标签: scala
== 被用作“后缀运算符”,因此您实际上是将函数 '\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
【讨论】:
'\t'.==。你说你正在传递一个函数,但混合中有重载和 eta 扩展。预期的类型至关重要。现在我必须赞成 b/c 赞成另一个答案。
是你的问题
count(p: (Char) ⇒ Boolean): Int?== 方法是另一个 char 上的布尔函数吗?答案:是的,是的。
【讨论】:
Malvolio。
在 scala 中,您可以通过这种方式传递谓词:
def predicate(ch: Char) = { ... }
string.count(ch => predicate(ch))
或者这样
string.count(predicate(_))
还有一种方法可以省略参数占位符,看起来确实不错
string.count(predicate)
在您的示例中,您实际上是在调用 Char 的方法 '==',因此它与上面的代码非常相似。只是更不可读。
string.count('\t'.==)
【讨论】: