What's so special about 'return' keyword

前端 未结 3 1143
眼角桃花
眼角桃花 2020-12-14 11:40

When I seemed to understand what return is for in Haskell, I tried to play with different alternatives and it seems that return not only can be used anywhere in the monad ch

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 11:47

    Mike Hartl comment led me to the right direction, although was not so formal imho, so I just post my final understanding what so special about 'return' operator.

    Any type class lists operator it supports and there are functions that can work only in this class context (imposed via class constratint symbol =>). So, for example filterM signature

    filterM :: Monad m => (a -> m Bool) -> [a] -> m [a] 
    

    shows us that it can be used only in monadic context. The magic is that in the body this function is free to use any operator the class has (>>= and return for Monad) and if an instance (for example my MaybeG ) lacks a method (return in my case) then the function can fail. So when the return is there

    > filterM (\x -> JustG (x > 0)) [2, 1, 0, -1] 
    JustG [2,1]
    

    and when it's commented (see my implementation of MaybeG in the question)

    > filterM (\x -> JustG (x > 0)) [2, 1, 0, -1] 
    
    *** Exception: Monad.hs:3:10-21: No instance nor default method for class operation GHC.Base.return
    

    so imlementation of any operator (return in monad case) is required if one plans to use the instance with functions working with this class (monad in this case) constraint.

    I think my initial misunderstanding was due to the fact that most tutorials explains monadic chains without polymorphic (ad hoc) context. This context in my opinion makes monads more powerful and reusable.

提交回复
热议问题