You simply pass the current best value as an additional argument to recursive calls and also return the updated best value as the a part of their results. So if you have a function of type a -> b
, it becomes something like a -> Int -> (b, Int)
. Instead of reading the global variable, you read the additional argument, and instead of writing it, you return a modified value when the function finishes.
This can be nicely expressed using the state monad. Type Int -> (b, Int)
is isomorphic to State Int b
, so our function of type a -> b
becomes a -> State Int b
.