What are free monads?

前端 未结 7 1253
孤城傲影
孤城傲影 2020-11-27 08:54

I\'ve seen the term Free Monad pop up every now and then for some time, but everyone just seems to use/discuss them without giving an explanation of what they are.

相关标签:
7条回答
  • 2020-11-27 09:35

    The Free Monad (data structure) is to the Monad (class) like the List (data structure) to the Monoid (class): It is the trivial implementation, where you can decide afterwards how the content will be combined.


    You probably know what a Monad is and that each Monad needs a specific (Monad-law abiding) implementation of either fmap + join + return or bind + return.

    Let us assume you have a Functor (an implementation of fmap) but the rest depends on values and choices made at run-time, which means that you want to be able to use the Monad properties but want to choose the Monad-functions afterwards.

    That can be done using the Free Monad (data structure), which wraps the Functor (type) in such a way so that the join is rather a stacking of those functors than a reduction.

    The real return and join you want to use, can now be given as parameters to the reduction function foldFree:

    foldFree :: Functor f => (a -> b) -> (f b -> b) -> Free f a -> b
    foldFree return join :: Monad m => Free m a -> m a
    

    To explain the types, we can replace Functor f with Monad m and b with (m a):

    foldFree :: Monad m => (a -> (m a)) -> (m (m a) -> (m a)) -> Free m a -> (m a)
    
    0 讨论(0)
提交回复
热议问题