DEV Community

Understanding the Fold Operation

Kasey Speakman on December 06, 2018

I recently ran across a video by Don Syme called F# Code I Love. It details some nice (and naughty 🎄) usage patterns in F#. I was very surprised to...
Collapse
 
jvanbruegge profile image
Jan van Brügge

There is no need to name inputList.

f x = x |> g
    where g = List.fold update initial
-- same as
f x = g x
-- same as 
f = g
-- with your names:
runChallenge = List.fold update initial
Collapse
 
kspeakman profile image
Kasey Speakman • Edited

Thanks for your comment.

I am aware of the forms you demonstrated. Rest assured that I chose the naming and structure very intentionally. I avoid point-free notation in most cases. Hidden parameters do not tend to help readability. Spelling out the parameter isn't as concise, but it is far more clear. Especially when the reader might not be as familiar with FP.

Collapse
 
jvanbruegge profile image
Jan van Brügge

It depends on your view on it. If you name the parameter, your view is "I will fold update over the list". Without the parameter your view is "runChallenge is a fold with update and some initial value". In my opinion this focuses on the algorithm and not the data making in easier to understand. A greater percentage of the code is thr actual algorithm as opposed to unnecessary stuff

Collapse
 
yawaramin profile image
Yawar Amin

Thanks for this very clear explanation. Do you remember the old days of Elm when it was FRP and there was a (I think) Signal.foldp function that was explained as 'returning a new state by folding over the past state and an event'? The theory behind folding is so generally applicable, it's quite fascinating.

Collapse
 
kspeakman profile image
Kasey Speakman

I was hoping someone would notice the similarity with MVU. :) In fact, I always found folds confusing until I realized that an Elm application (even today) is just a fold. (And the view function is a transformation run on the model after each fold step.) And so, adopting the same strategy used by MVU enables a straight-forward definition of fold.

Thanks for the comment!