Is there anything we lose with MonoFoldable?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 22:15:20

问题


MonoFoldable in the mono-traversable package seems to be able to implement all of the usual Foldable containers and more, for example, things like Bytestring and homogeneous tuples can be made MonoFoldable but not Foldable. My question is, do we lose anything from MonoFoldable that we don't have in Foldable, aside from requiring some advanced GHC features, making it slightly more tricky for instance writers and perhaps getting uglier error messages?

For example, is there some code which when using Foldable compiles but with MonoFoldable types are not inferred for example? Or anything else that makes client (not instance writer code) significantly simpler with Foldable than MonoFoldable?


回答1:


You lose parametricity.

A type (Foldable f) => f a -> [a] provides significantly different guarantees than (MonoFoldable c) => c -> [Element c].

You can play with a free theorem generator to get some ideas of the properties, but as a simple example the former type provides the property that any element in the output must occur in the input. This property is in no way guaranteed by the latter type.




回答2:


The biggest thing you lose is polymorphic recursion. Consider Okasaki's catenable lists:

data Cat q a = Empty | Cat a (q (Cat q a))

We can write

instance Foldable q => Foldable (Cat q) where
   foldMap _ Empty = mempty
   foldMap f (Cat a q) = f a <> foldMap (foldMap f) q

But if we try to use just MonoFoldable, we're stuck. The necessary instance constraint on q, forall x . (MonoFoldable (q x), Element (q x) ~ x), can't be expressed in any usual fashion. It's probably possible to work around that with Data.Constraint.Forall, but it gets pretty ugly.


A smaller problem is that code may get more complex type signatures. For example,

osum :: (MonoFoldable c, Num (Element c)) => c -> Element c

strikes me as inferior to

sum :: (Foldable f, Num n) => f n -> n

The fix is easy: change the definition of MonoFoldable to

class (a ~ Element c) => MonoFoldable' a c where ...

which would give you

osum' :: (MonoFoldable' n c, Num n) => c -> n

Alternatively, scrap Element altogether, and use

class MonoFoldable'' a c | c -> a

which gives a similarly simplified signature.

Unfortunately, Michael Snoyman disagrees with me on this point. I may write my own wrapper package some time to expose my preferred API.



来源:https://stackoverflow.com/questions/39634504/is-there-anything-we-lose-with-monofoldable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!