06 Jan

Fold versus Reduce

André van Meulebrouck makes the comment that, in Volume I, there are instances where I should be using List.Reduce as opposed to List.Fold. I don’t deny that this is the case; firstly, let’s clarify the difference between the two functions as used for F# collections in general…

Fold requires a “starting value” into which elements are to be collated; the starting value can be any primitive F# type – I often use a string. Conversely, Reduce does not require a starting value consequently, the type used in the Reduce anonymous function must be of the same type as expressed by the collection (elements) one is folding.

I would be hard-pressed to quantify general processing performance differences between Fold and Reduce but I suspect that Reduce is faster since the accumulator and element value types must, by definition, all have the same primitive type. I guess the “general rule” about making a choice between the two is that if your accumulator is going to be the same primitive type as your collection elements then use Reduce – otherwise, use Fold since there will be some implicit casting involved – even if only in using the string representation (ToString()) of a collection element to enable the accumulator to “work”.

Leave a Reply

Contact Form

Contact Form

You may use this form to send me an email…
Click on the panel tab or elsewhere on the screen to close this panel.