Which one is the appropriate morphism (recursion scheme) to use when the given item's position (index, or path) is required in the transformer function?
A simple example would be transforming a list ["foo", "bar", "qux"]
into the string "foo, bar, and qux"
. The current element's position is needed to know when to insert the and
.
You need to make the index part of the structure so it is available to the recursion scheme. An ad-hoc way to do this is to define a
foldWithIndex
function:This function takes an operator for combining the elements which also considers the index:
results in
"foo, bar and qux"
.For a more general approach see
Data.Foldable.WithIndex
, which provides a foldable typeclass that also takes an index into account.