-1

当我有一个字符串变量x时,由于某种原因是""

val x = ""

我做到了: x.forall(_.isDigit)它返回true

我有点纳闷,为什么是真的,不应该是假的吗?当我的 if 条件不起作用时,我很难发现这一点。然后我去看了Scala源码:

private def prefixLengthImpl(p: A => Boolean, expectTrue: Boolean): Int = {
    var i = 0
    while (i < length && p(apply(i)) == expectTrue) i += 1
    i
  }

  override /*IterableLike*/
  def forall(p: A => Boolean): Boolean = prefixLengthImpl(p, expectTrue = true) == length

所以显然它持有“虚无真相”原则,并且由于计数器变量i返回为0并且我的字符串的长度也是0,它最终是0==0因此true。我发现x.isEmpty在做forall.

4

3 回答 3

6

I don't see the problem. The scala forall method follows the basic first-order logic, which minimizes surprise. For your specific example you should probably be using the regex "".matches("\\d+") anyway.

于 2013-03-21T17:21:47.437 回答
0

http://en.wikipedia.org/wiki/Vacuous_truth

事实上,“”中的每个字符都是一个数字。

于 2013-03-21T18:37:47.013 回答
0

你可以forall结合exists

str.exists(_.isDigit) && str.forall(_.isDigit)
// returns true for "123", false for "", false for "1nodigits"
于 2013-03-21T17:32:18.967 回答