下面是實現該功能的另一種方式:
scala> def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] =
| List.iterate(ls, ls.size)(_.tail).flatMap(f)
flatMapSublists: [A, B](ls: List[A])(f: List[A] => List[B])List[B]
一個簡單的戴夫的flatMapSublistsTR和我之間的比較:
scala> def time(count: Int)(call : => Unit):Long = {
| val start = System.currentTimeMillis
| var cnt = count
| while(cnt > 0) {
| cnt -= 1
| call
| }
| System.currentTimeMillis - start
| }
time: (count: Int)(call: => Unit)Long
scala> val xs = List.range(0,100)
scala> val fn = identity[List[Int]] _
fn: List[Int] => List[Int] = <function1>
scala> time(10000){ flatMapSublists(xs)(fn) }
res1: Long = 5732
scala> time(10000){ flatMapSublistsTR(xs)(fn) }
res2: Long = 347232
凡方法flatMapSublistsTR被實現爲:
def flatMapSublistsTR[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] = {
@annotation.tailrec
def helper(r: List[B], ls: List[A]): List[B] = {
ls match {
case Nil => r
case [email protected](_ :: tail) => helper(r ::: f(sublist), tail)
}
}
helper(Nil, ls)
}
Your resu因爲原來的錯誤順序是錯誤的,所以你拿出當前的結果並追加所有剩下的結果。在您的TR版本中,您的列表'r'正在執行所有先前的結果,因此您需要將當前結果附加到該列表。 –
@LuigiPlinge謝謝! – leedm777