据我所知,该isDefinedAt
方法应该像类型contains
方法一样工作。但奇怪的是,它的行为不同——它不检查元素是否重复出现。
val randomizer = new Random
def next(acc: List[Int], n: Int): List[Int] = {
if(n > 0) {
val r = randomizer.nextInt(15)
println("generating, r=" + r + " is defined=" + acc.isDefinedAt(r))
if(!acc.isDefinedAt(r)) next(r :: acc, n - 1) // check for NO coincidence
else next(acc, n)
} else acc
}
println("indices = " + next(List[Int](), 6))
当然,我可以为此使用 Sets 而不是列表,但是,为什么它会这样呢?
我得到的输出就像
generating, r=8 is defined=false
generating, r=13 is defined=false
generating, r=2 is defined=false
generating, r=8 is defined=false
generating, r=9 is defined=false
generating, r=3 is defined=true
generating, r=2 is defined=true
generating, r=7 is defined=false
indices = List(7, 9, 8, 2, 13, 8)