This is quite a simple way to think about foldl
, which is not a natural fold on lists, but can still be quite useful sometimes. (Geraint Jones calls it loop
instead, which is in some ways a much better name.)
Take a look at the foldl
function (or one formulation of it):
It might be initially unclear what this function is doing exactly - for me, at least, it’s less obvious than foldr
.
Here’s a frame for thinking about it: consider the following imperative Python program for converting hexadecimal numbers, using a deque as a stack:
The above Python program is analogous to the following in Haskell:
The analogy is that there is a variable (x
in the Python program) that is initially set to the value v
. Then there is iteration through the stack, each time updating v
according to some function, g
in the Python and f
in the Haskell.