The documentation for Foldable
lists several properties that are demanded of "general Foldable structures":
For
foldr
:For a general Foldable structure this should be semantically identical to,
foldr f z = foldr f z . toList
For
foldl
:For a general Foldable structure this should be semantically identical to,
foldl f z = foldl f z . toList
For
foldl'
(with what looks like a typo to me):For a general Foldable structure this should be semantically identical to,
foldl f z = foldl' f z . toList
What are some instances of Foldable
where these properties need not or cannot hold?
As I understand it, these are rules that an instance must obey if it defines those optional functions. By default, a
Foldable
instance only has to define eitherfoldMap
orfoldr
. From one of those two definitions, all the other functions of the type class follow automatically.Often, however, type classes give you the option to define more of the type class' behaviour. This can be useful if the default, automatic definition of, say,
toList
is inefficient, and you wish to supply a more efficient implementation. This may be easier to understand for theMonoid
type class, which definesmconcat
as an optional function "so that an optimized version can be provided for specific types".The laws quoted in the OP are laws that an instance must obey if you choose to define some or all of these functions yourself. As an example of a (nonsensical) type that breaks the rules, consider this
Invalid
type:While it only has to define
foldMap
to be aFoldable
instance, this one also definesfoldr
andtoList
. While thetoList
definition is fine, thefoldr
definition breaks the rules:The
toList
andfoldMap
functions behave like you'd expect them to behave, but notice thatfoldr f z
doesn't produce the same output asfoldr f z . toList
.While
Invalid
is a nonsensical example, it demonstrates that you can write code that compiles and looks like it provides an instance ofFoldable
. The laws and rules associated with each function, however, makes it clear that this is not a valid instance.