How to extract value from monadic action

前端 未结 8 2345

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 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.

提交回复
热议问题