简体   繁体   中英

If a data structure is foldable, is it a monoid?

Obviously, if a data structure is a monoid, it's foldable, but is it safe to say if a data structure is foldable, it's a monoid?

https://en.wikibooks.org/wiki/Haskell/Foldable

If a data structure is foldable, is it a monoid?

Your claim "if a data structure is a Monoid then it is Foldable " is not reasonably true. For example:

newtype ActionList a = ActionList (IO [a])

instance Monoid (ActionList a) where
    mempty = ActionList (return [])
    ActionList a `mappend` ActionList b = ActionList (liftA2 (++) a b)

This is a perfectly good monoid. But because all of its values are under IO , you can't observe any of them from Foldable . The only Foldable instance would be the one that always returns empty (technically this would be valid because foldMap doesn't really have any laws about its validity, but it would hard to say that this is a good instance with a straight face).

The converse, which you are asking about, is also not true. For example:

data TwoThings a = TwoThings a a

This is foldable:

instance Foldable TwoThings where
    foldMap f (TwoThings x y) = f x <> f y

However, if something is both a Foldable and a Monoid in any related way, I would expect the following homomorphism laws to hold:

foldMap f mempty = mempty
foldMap f (a <> b) = foldMap f a <> foldMap f b

And we can't get these laws to hold for TwoThings . Notice that foldMap (:[]) a for TwoThings always has two elements. But then the second law has two elements on the left and four on the right. But the laws are not required to find a counterexample, as dfeuer's answer shows.

Here's something Foldable (even Traversable ) that has no hope of being a Monoid :

{-# language EmptyCase #-}

data F a

instance Foldable F where
  foldMap _ t = case t of
  -- or, = mempty
instance Traversable F where
  traverse _ t = case t of
  -- or, = pure $ case t of

instance Semigroup (F a) where
  -- the only option
  x <> _ = x

instance Monoid (F a) where
  mempty = ????

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM