The difference between reduction and flexion

After reading this article about the vs fold abbreviation in Scala http://josephmoniz.imtqy.com/blog/2013/04/04/scala-reduce-vs-fold/ , it says: "You take some value of N and perform aggregation operations on it so the end result is usually some value <= N. "

But is this statement false, since summing over N values ​​causes a value> = N?

Update: I think <= in this case means the same type or subtype

+7
scala
source share
4 answers

I consider this an erroneous characteristic. It’s better to think of it this way:

In: initial value way to combine stuff with initial value collection Out: combined stuff 

And reduce it like this:

 In: way to combine stuff collection Out: combined stuff 

That is, the difference is whether you have an initial value (which may not even be the same type as your collection!), As the fold does, or just dump the values ​​that you already have, as the reduction does .

If you have a natural zero, that is, something that can be combined without changing what it is combined with, then you can implement a reduction in the form of a reset, starting from zero. For example, for multiplication, zero is 1 (because 1*x == x ), therefore

 List(1,2,3).fold(1){_ * _} List(1,2,3).reduce{_ * _} 

give the same answer. (However, only the first gives an answer in an empty list!)

To see an example of how fold is completely more general, consider this: here with foldLeft so that we know that the initial value is passed on the left side of the operation -

 List(1,2,3).foldLeft(List(0))((ns,n) => ns ++ List.fill(n+1)(n)) 

which gives List(0, 1, 1, 2, 2, 2, 3, 3, 3, 3) .

+12
source share

reduce uses a concept called "monoid" to get a "zero value" as an initializer for the drive in a folded form *

+3
source share

Fold needs a "start element", the abbreviation will automatically accept the first element of the sequence as the starting one, so they are equivalent to some extent:

 val L = List(1,2,3,4) val H = L.head val T = L.tail L.reduce(_+_) ~== T.fold(H)(_+_) 

Reduce compactness, but with a difference, you have the opportunity to provide another launch element and change the result of the operation, therefore:

 2014 + L.reduce(_+_) ~== L.fold(2014)(_+_) // NB: here we use L, not T for fold 

Things will be more exciting and more fold-friendly when you exit simple arithmetic into more complex binary operations like Set + Int:

 List(1,2,3,3,2,2,1).foldLeft(Set[Int]())(_ + _) // will produce Set(1, 2, 3) 

... you can drop the JDBC update challenge :).

+2
source share

see here:

difference between foldLeft and reduceLeft in Scala

reduce and collapse shortcuts for reduceLeft and foldLeft

0
source share

All Articles