The correct answer is
No, you can't!
Well, yes, GHC has a thing called unsafePerformIO
, but this is not part of the Haskell standard, merely a hack to allow certain “morally pure” functions from other languages to be called using the foreign function interface, and reflect the type of those functions with the type they would have if you'd written them straight in pure Haskell.
Note that “unwrapping the IO
monad” would not simply give you the result of that computation. If IO
were a public-constructors type, it would actually look (conceptually) something like the following:
data IO' a =
WriteToFile FilePath String
| PutStr String
| WithStdLine (String -> IO' a)
| ...
| SequenceIO (IO' ()) (IO' a)
Pattern matching on such an IO' a
value would normally not give you access to anything of type a
, it would merely give you some description of actions to be performed, and perhaps some function that could possibly yield an a
value from intermediate results obtained from the environment.
The only way to actually get useful work done would then still be like it is now: by binding it to something like the main
action, which then executed by some “real world entity” (the runtime).
If you want to implement an algorithm that describes a proper mathematical (i.e. pure) function but seems to lend itself to an imperative programming style with mutation etc., then you should not implement this in the IO
monad at all. You might well be able to just implement it in ordinary pure Haskell98 by just choosing suitable data structures, or perhaps it makes sense to use the ST
monad to achieve e.g. array updates with the same performance they'd have in imperative languages.
ST
for locally impure operations. - LeeMonad
. Considerdata Proxy a = Proxy
(Note that there is no value "contained in"Proxy
at all) which is aMonad
. - David YoungIO
by design, because its very purpose is to mark operations that are necessarily implemented by the compiler, not in Haskell code. - chepnerST
is what he's looking for. While it is a good solution for many problems, he has yet to state a need and his one example wastrace
- certainly not anST
sort of task. @yanpas Can you please be more specific as to your actual goal? - Thomas M. DuBuisson