Are there laws for the Foldable typeclass that constrain how Foldable instances can be derived?
No, there are no laws that tell what order fields must be visited in. It is conventional to visit fields in the order they appear in the data structure definition (or at least the user-visible API, if pattern synonyms are used), but this is convention only.
Foldable
itself is very poor in laws. The fundamental method is foldMap
. Other methods are expected to behave like their default definitions up to laziness details. Two laws arise from parametricity:
If
g :: m -> n
is a monoid morphism andf :: a -> m
is a function, theng . foldMap f = foldMap (g . f)
If the
Foldable
is also aFunctor
, then for all functionsg :: b -> m
andf :: a -> b
,foldMap (g . f) = foldMap g . fmap f
In practice, most Foldable
instances are also Traversable
. Traversable
has much richer laws for traverse
, and imposes the law that
foldMap f = getConst . traverse (Const . f)
This guarantees that for a Traversable
, every element in the container is folded over exactly once. Whereas
instance Foldable [] where
foldMap _ [] = mempty
foldMap f (x:_:xs) = f x <> f x <> foldMap f xs
would be perfectly valid, there's no lawful Traversable
instance that matches.
Foldable
has no laws guiding the order of traversal. In fact, we can think of the act of writing a Foldable
instance as choosing a specific order of traversal. If DeriveFoldable
is used, the choice will be to follow the order of the fields in the definition of the type (see also Daniel Wagner's answer); the details are documented in the relevant section of the GHC User's Guide.
(Side note: As discussed in dfeuer's answer, Traversable
has richer laws that, among other things, limit the range of acceptable foldMap
implementations. Still, both inorder and preorder traversals for your Tree
give out lawful implementations of Traversable
.)