Zimo Li
Zimo Li

Zimo Li

Scala Reduce vs Fold

Zimo Li's photo
Zimo Li
·May 24, 2022·

There is only a subtle difference between reduce and fold. Fold requires an initial value, whereas reduce doesn’t need one.

Reduce example:

scala> (1 to 10).reduce(_ * _)
val res0: Int = 3628800

Fold example:

scala> (1 to 10).fold(0)(_ * _)
val res0: Int = 0

scala> (1 to 10).fold(1)(_ * _)
val res1: Int = 3628800

This is because reduce requires the operator to be both commutative and associative, whereas fold requires the operator to be associative only.

A reminder of some basic arithmetics concepts:

Commutative property: \[ a + b = b + c \]

Associative property: \[ (a + b) + c= a + (b + c) \]

 
Share this