The type Fold m a b represents a consumer of an input stream of values
of type a and returning a final value of type b in Monad m. The
constructor of a fold is Fold step initial extract final.
The fold uses an internal state of type s. The initial value of the state
s is created by initial. This function is called once and only once
before the fold starts consuming input. Any resource allocation can be done
in this function.
The step function is called on each input, it consumes an input and
returns the next intermediate state (see Step) or the final result b if
the fold terminates.
If the fold is used as a scan, the extract function is used by the scan
driver to map the current state s of the fold to the fold result. Thus
extract can be called multiple times. In some folds, where scanning does
not make sense, this function is left unimplemented; such folds cannot be
used as scans.
Before a fold terminates, final is called once and only once (unless the
fold terminated in initial itself). Any resources allocated by initial
can be released in final. In folds that do not require any cleanup
extract and final are typically the same.
When implementing fold combinators, care should be taken to cleanup any
state of the argument folds held by the fold by calling the respective
final at all exit points of the fold. Also, final should not be called
more than once. Note that if a fold terminates by Done constructor, there
is no state to cleanup.
NOTE: The constructor is not yet released, smart constructors are provided
to create folds.
Constructors
forall s. Fold (s -> a -> m (Step s b)) (m (Step s b)) (s -> m b) (s -> m b)Fold step initial extract final