List foldRight Always Using foldLeft?

前端 未结 1 1178
感动是毒
感动是毒 2021-01-11 19:58

I just looked at the List.scala’s implementation of foldRight().

  override def reverse: List[A] = {
    var result: List[A] = Nil
    var these         


        
相关标签:
1条回答
  • 2021-01-11 20:36

    foldLeft is tail-recursive, reverse isn't recursive at all: this implementation ensures constant memory usage. foldRight, when not implemented in terms of foldLeft, isn't tail-recursive, which makes it unsafe for large amounts of data.

    Note: there might be ways to make foldRight tail-recursive, but all those I can think of need to append things at the end of a list, which means traverse it in its entirety. If you're going to do that anyway, better use foldLeft and reverse the result, it involves far fewer full iterations on the whole list.

    0 讨论(0)
提交回复
热议问题