What are free monads?

前端 未结 7 1262
孤城傲影
孤城傲影 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:14

    A Haskell free monad is a list of functors. Compare:

    data List a   = Nil    | Cons  a (List a  )
    
    data Free f r = Pure r | Free (f (Free f r))
    

    Pure is analogous to Nil and Free is analogous to Cons. A free monad stores a list of functors instead of a list of values. Technically, you could implement free monads using a different data type, but any implementation should be isomorphic to the above one.

    You use free monads whenever you need an abstract syntax tree. The base functor of the free monad is the shape of each step of the syntax tree.

    My post, which somebody already linked, gives several examples of how to build abstract syntax trees with free monads

提交回复
热议问题