difference between foldLeft and reduceLeft in Scala

后端 未结 7 2032
野性不改
野性不改 2020-12-12 08:49

I have learned the basic difference between foldLeft and reduceLeft

foldLeft:

  • initial value has to be passed
7条回答
  •  长情又很酷
    2020-12-12 09:13

    From Functional Programming Principles in Scala (Martin Odersky):

    The function reduceLeft is defined in terms of a more general function, foldLeft.

    foldLeft is like reduceLeft but takes an accumulator z, as an additional parameter, which is returned when foldLeft is called on an empty list:

    (List (x1, ..., xn) foldLeft z)(op) = (...(z op x1) op ...) op x

    [as opposed to reduceLeft, which throws an exception when called on an empty list.]

    The course (see lecture 5.5) provides abstract definitions of these functions, which illustrates their differences, although they are very similar in their use of pattern matching and recursion.

    abstract class List[T] { ...
      def reduceLeft(op: (T,T)=>T) : T = this match{
        case Nil     => throw new Error("Nil.reduceLeft")
        case x :: xs => (xs foldLeft x)(op)
      }
      def foldLeft[U](z: U)(op: (U,T)=>U): U = this match{
        case Nil     => z
        case x :: xs => (xs foldLeft op(z, x))(op)
      }
    }
    

    Note that foldLeft returns a value of type U, which is not necessarily the same type as List[T], but reduceLeft returns a value of the same type as the list).

提交回复
热议问题