Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

instance Foldable f => Foldable1 (Cofree f) #157

Open
Icelandjack opened this issue Jun 11, 2017 · 5 comments
Open

instance Foldable f => Foldable1 (Cofree f) #157

Icelandjack opened this issue Jun 11, 2017 · 5 comments

Comments

@Icelandjack
Copy link

I wondered if the constraint on Foldable1 (Cofree f) could be weakened, this is my attempt

instance Foldable f => Foldable1 (Cofree f) where
  foldMap1 :: Semigroup m => (a -> m) -> (Cofree f a -> m)
  foldMap1 f (a :< (!as)) =
    foldMap1 f (a :| toList (foldMap (foldMap1 Single) as))

data FMG a = None | Single a | FMG a :<> FMG a
  deriving Foldable

instance Semigroup (FMG a) where
  (<>) = (:<>)

instance Monoid (FMG a) where
  mempty = None
  mappend = (:<>)
@Icelandjack
Copy link
Author

I want a more elegant solution to this, but the instance makes sense: Cofree Maybe is the non-empty list and as such should have a Foldable1 instance even though Maybe is just Foldable. This can probably be nicer using reflection

@ElvishJerricco
Copy link
Collaborator

ElvishJerricco commented Jun 11, 2017

Just freely lift the semigroup to a monoid using Option and use foldMap. I'm on mobile, so forgive me if this doesn't compile or has typos:

instance Foldable f => Foldable1 (Cofree f) where
  foldMap1 f (a :< as) = case getOption $ foldMap (Option . Just . foldMap1 f) as of
    Just b -> f a <> b
    Nothing -> f a

@Icelandjack
Copy link
Author

That compiles smoothly and answers my question, I imagine the same can be written for Traversable1.. it always fun when the context differs like this.

Should this be added?

@xuwei-k
Copy link

xuwei-k commented Jun 13, 2017

FYI scalaz/scalaz@a05ab2c in scalaz

@andrewthad
Copy link

What's the status of this? @ElvishJerricco Would you take a PR for weakening the Foldable1 constraint in the instance head to Foldable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants