What was wrong with Control.MonadPlus.Free?

人盡茶涼 提交于 2019-12-01 14:38:33

问题


The free MonadPlus defined as

data Free f a = Pure a | Free (f (Free f a)) | Plus [Free f a]

was removed in free 4.6 with the following remark (changelog):

Removed Control.MonadPlus.Free. Use FreeT f [] instead and the result will be law-abiding.

What was the problem, in particular, what laws didn't hold?


回答1:


According to this issue in the bug tracker the old definition does not obey the associative law.


Although I know little about such things, I suspect an other problem is redundancy:

Pure a
Plus [Pure a]
Plus [Plus [Pure a]]
...

all seem to represent the same thing. Free structures are generally supposed to be unique. There are times when they cannot be represented uniquely (e.g., free abelian groups) but when possible they should be.

Actually, I think the suggested alternative suffers from the same problem, although it might be possible to repair it by using NonEmpty instead of []. So this change could just be a matter of removing excess cruft from the library.




回答2:


I believe that the representation itself was OK and that the lawfulness could have been remedied by changing these method signatures

iter :: Functor f => (f a -> a) -> ([a] -> a) -> Free f a -> a
iterM :: (Monad m, Functor f) => (f (m a) -> m a) -> ([m a] -> m a) -> Free f a -> m a

to

iter :: (Functor f, Monoid a) => (f a -> a) -> Free f a -> a
iterM :: (MonadPlus m, Functor f) => (f (m a) -> m a) -> Free f a -> m a

i.e.

  • use Monoid a instead of an arbitrary function [a] -> a in iter;
  • use MonadPlus m instead of an arbitrary function [m a] -> m a in iterM.

My guess is that it was removed (instead of fixed) just because it is not worth to keep around when FreeT f [] gives an equivalent representation.



来源:https://stackoverflow.com/questions/32185389/what-was-wrong-with-control-monadplus-free

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