How to extract value from monadic action

前端 未结 8 2155

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:54

    There is a useful extract function and some other functions related to this at http://hackage.haskell.org/package/comonad-5.0.4/docs/Control-Comonad.html

    It's only defined for some functors/monads and it doesn't necessarily give you the whole answer but rather gives an answer. Thus there will be possible subclasses of comonad that give you intermediate stages of picking the answer where you could control it. Probably related to the possible subclasses of Traversable. I don't know if such things are defined anywhere.

    Why hoogle doesn't list this function at all appears to be because the comonad package isn't indexed otherwise I think the Monad constraint would be warned and extract would be in the results for those Monads with a Comonad instance. Perhaps this is because the hoogle parser is incomplete and fails on some lines of code.

    My alternative answers:

    1. you can perform a - possibly recursive - case analysis if you've imported the type's constructors
    2. You can slink your code that would use the extracted values into the monad using monad >>= \a -> return $ your code uses a here as an alternative code structure and as long as you can convert the monad to "IO ()" in a way that prints your outputs you're done. This doesn't look like extraction but maths isn't the same as the real world.
    0 讨论(0)
  • 2020-11-27 06:01

    Suppose there was such a function:

    extract :: Monad m => m a -> a
    

    Now you could write a "function" like this:

    appendLine :: String -> String
    appendLine str = str ++ extract getLine
    

    Unless the extract function was guaranteed never to terminate, this would violate referential transparency, because the result of appendLine "foo" would (a) depend on something other than "foo", (b) evaluate to different values when evaluated in different contexts.

    Or in simpler words, if there was an actually useful extract operation Haskell would not be purely functional.

    0 讨论(0)
提交回复
热议问题