How to extract value from monadic action

前端 未结 8 2323

Is there a built-in function with signature :: (Monad m) => m a -> a ?

Hoogle tells that there is no such function.

Can you explain why?<

8条回答
  •  暖寄归人
    2020-11-27 05:37

    Is there a build-in function with signature :: (Monad m) => m a -> a ?

    If Hoogle says there isn't...then there probably isn't, assuming your definition of "built in" is "in the base libraries".

    Hoogle tells that there is no such function. Can you explain why?

    That's easy, because Hoogle didn't find any function in the base libraries that matches that type signature!

    More seriously, I suppose you were asking for the monadic explanation. The issues are safety and meaning. (See also my previous thoughts on magicMonadUnwrap :: Monad m => m a -> a)

    Suppose I tell you I have a value which has the type [Int]. Since we know that [] is a monad, this is similar to telling you I have a value which has the type Monad m => m Int. So let's suppose you want to get the Int out of that [Int]. Well, which Int do you want? The first one? The last one? What if the value I told you about is actually an empty list? In that case, there isn't even an Int to give you! So for lists, it is unsafe to try and extract a single value willy-nilly like that. Even when it is safe (a non-empty list), you need a list-specific function (for example, head) to clarify what you mean by desiring f :: [Int] -> Int. Hopefully you can intuit from here that the meaning of Monad m => m a -> a is simply not well defined. It could hold multiple meanings for the same monad, or it could mean absolutely nothing at all for some monads, and sometimes, it's just simply not safe.

提交回复
热议问题