Skip to content

Explicitly define length, elem, etc. in Foldable instance for Data.Functor.Compose #57

Closed
@cdsmith

Description

@cdsmith

Currently, the Foldable instance for Data.Functor.Compose looks like this:

instance (Foldable f, Foldable g) => Foldable (Compose f g) where
    foldMap f (Compose t) = foldMap (foldMap f) t

All other methods besides foldMap get default implementations, which delegate to foldMap. I propose that the following should be added:

    length (Compose t) = getSum (foldMap' (Sum . length) t)
    elem x (Compose t) = getAny (foldMap' (Any . elem x) t)
    sum (Compose t) = getSum (foldMap' (Sum . sum) t)
    product (Compose t) = getProduct (foldMap' (Product . product) t)
    ... and so on

The inner container in a Compose may have a more efficient implementation for other methods of Foldable. In case it does, that should be used instead of falling back to foldMap as happens now.

This applies to all members of Foldable, which presumably are in the class precisely because they can have more efficient implementations. It seems particularly troublesome for length and elem, which are likely to have much more efficient implementations for commonly used containers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    approvedApproved by CLC votebase-4.19Implemented in base-4.19 (GHC 9.8)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions