Skip to content

Missing combinators for creating and consuming Fold1, and IndexedFold1 's  #1015

@noinia

Description

@noinia

When working with Fold1 and/or IndexedFold1's it would be nice to have functions such as 'folding1' and 'ifolding1' to build the appropriate non-empty folds, and an indexed version of 'toNonEmptyOf' to consume them. In particular, I would suggest the following implementations:

-- | construct a Fold1 from a function that produces a Foldable1
folding1         :: Foldable1 f => (s -> f a) -> Fold1 s a
folding1 sfa agb = phantom . traverse1_ agb . sfa
{-# INLINE folding1 #-}

-- | Version of ifolding to build an 'IndexedFold1'
ifolding1       :: (Foldable1 f, Indexable i p, Contravariant g, Apply g)
                => (s -> f (i, a)) -> Over p g s t a b
ifolding1 sfa f = phantom . traverse1_ (phantom . uncurry (indexed f)) . sfa
{-# INLINE ifolding1 #-}

-- | indexed version of 'toNonEmptyOf'
itoNonEmptyOf   :: IndexedGetting i (NonEmptyDList (i,a)) s a -> s -> NonEmpty (i,a)
itoNonEmptyOf l = flip getNonEmptyDList [] . ifoldMapOf l (\i a -> NonEmptyDList $ ((i,a) :|))
{-# INLINE itoNonEmptyOf #-}

The implementations of folding1 and ifolding1 are almost identical to folding and ifolding (but with a different typeclass constraint). The implementation of iToNonEmptyOf was adapted from toNonEmptyOf

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions