Full source code ⋅ Next chapter
A farmer with a wolf, a goat, and a cabbage must cross a river by boat. The boat can carry only the farmer and a single item. If left unattended together, the wolf would eat the goat, or the goat would eat the cabbage. The farmer must help them all cross the river without anything being eaten.
By solving this puzzle we constantly need to choose between items so let's model it with a Sum:
Therefore deconstructing item (knowing which option is there) is essentially factoring through a Sum:
It's possible to express it shorter but then we loose visual tips - it's getting more important if Sum is big like Latin:
If you don't want to deconstruct Sum manually it's possible to use equality relation:
We can wrap this expression into a logical predicate:
The main advantage is that we get a contravariant functor:
Its parameter positioned contravariantly is effectively its representing object:
Another use case of factoring through a Sum is co-representing datastructures:
Unlike Match List of any size is a covariant functor:
We need this covariant functor to track content of the river shores between transitions - there are two cases that are considered unacceptable a boat to leave to due to some creatures meal preferences:
We already have logical predicates - but they are defined for individual items. Can we somehow make them work for list of items? Yes.
At first sight they seem incompatible - Match is contravariant and List is covariant therefore there is no natural transformation between them... but there is at least one between their compositions! If variances of two functors are not the same - their composition is contravariant.
If we first map over covariantly a lax Kleisli morphism and then apply a component of that natural transformation that swaps functors we get lax Kleisli morphisms at both source and target categories:
There is an operator for such a mappings arrangement:
Having a list of items, we can turn each of them into a logical predicate that compare another item to original one and then turn a list inside out so that we get a predicate on a list of items:
No matter of order this logical predicate is satisfied only if all items listed are found:
Congratulations, we just designed conditionals upon which we make stateful transitions!
In the next chapter we will focus on State mechanics for finding possible solutions.