2016-12-30 63 views
0

我的閱讀列表的斯卡拉API,我發現:的indexOf(ELEM:A,從爲:int) Scala List indexOf有bug?

所以我運行下面的代碼:

scala> List(1,3,5,8).indexOf(8,-2) 
res393: Int = 1 

scala> List(1,3,5,8).indexOf(8,-3) 
res391: Int = 0 

爲什麼是這樣的結果? 我的Scala版本是2.12.1(Java HotSpot™64位服務器VM,Java 1.8.0)。

+0

Doc鏈接:http://www.scala-lang.org/api/current/scala/collection/immutable/List.html#indexOf(elem:A,from:Int):Int – lambdie

+0

看來, 'from'參數的負值是未定義的。如果你嘗試像'Vector(1,3,5,8).indexOf(8,-2)'那樣運行'Vector',它將返回'3'。 – adamwy

+0

我認爲它是一個錯誤,應該報告!在Spark 2.12.1中,爲Vector和其他'SeqLike'實現(見https://issues.scala-lang.org/browse/SI-9936)修復了一個類似的錯誤 - 但只修復了「SeqLike」,而「LineraSeqOptimized '不是 - 見https://github.com/scala/scala/blob/v2.12.1/src/library/scala/collection/LinearSeqOptimized.scala#L294 –

回答

0

一個bug(儘管確實有預期的結果沒有明確的文件時from爲負) - 和感謝你的問題,這將是固定在2.12.2:https://github.com/scala/scala/pull/5621

所以 - 好趕上!

1

此行爲不是一個錯誤,只是未定義(雖然相當令人驚訝,而且取決於您使用的集合不一致)。


List.indexOf將最終調用.indexWhere(上LinearSeqOptimized),其中負號最終將移位結果:

override /*SeqLike*/ 
def indexWhere(p: A => Boolean, from: Int): Int = { 
    var i = from     // -3 
    var these = this drop from // no effect 
    while (these.nonEmpty) { 
    if (p(these.head)) 
     return i     // may return a negative number 

    i += 1 
    these = these.tail 
    } 
    -1 
} 

作爲評價注意到@adamwy ,撥打.indexOfVector的負數不會有相同的結果;它會調用.indexWhere(上IndexedSeqOptimized):

override /*SeqLike*/ 
def indexWhere(p: A => Boolean, from: Int): Int = { 
    val start = from max 0  // completely ignores negatives 'from' input 
    negLength(start + segmentLength(!p(_), start)) 
} 
+0

不是說它會有所作爲,你是對的,但不是'LinearSeqOptimized'中定義的'List'的'indexWhere'? – fxlae

+0

@fxlae:你說得對,修好了,謝謝。 – Marth

相關問題