4

I have a function that returns me IO (Map.Map String Double) and I need Map.Map String Double, without IO.

I tried to do this, but it fails with: Not in scope: data constructor `IO'.

extractIO (IO (a)) = a
Alin Ciocan
  • 3,082
  • 4
  • 34
  • 47
  • 5
    It's intentional that generally, you can't get out of `IO`. (If you absolutely have to, there is a way.) `IO` separates the pure stuff from the tainted that requires interaction with the exterior like reading files or getting user input. You can bind the result to a name, `theMap <- thingThatCreatesMap` and use that in pure computations called from the `IO`-action. – Daniel Fischer May 27 '13 at 12:50
  • 1
    See also `fmap`, which lets you apply a function to the value that the `IO` wraps. When you specialize `fmap` to `IO`, it has the type: `(a -> b) -> IO a -> IO b`. – Gabriella Gonzalez May 27 '13 at 15:58
  • 1
    The idea is that you don't get things *out* of `IO`. Instead you use Monad features to push things *into* `IO`, where you can safely combine them with the values that were required to be in `IO` (e.g. `fmap` can turn normal functions `a -> b` into functions `IO a -> IO b`, which you can then apply to your `IO a` values). – Ben May 28 '13 at 03:12

2 Answers2

14

You can't just unwrap IO, that's the entire point of IO.

If you have an IO (Map.Map String Double) and you want to process that thing, you have to do it within monadic context, i.e.

stuff :: IO ()
stuff = do
  map <- theThingThatReturnsYourIOMap
  theThingThatNeedsYourUnwrappedMap map

If you explain in more detail what you want to do, we can give you a more detailed answer.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
1

http://cvs.haskell.org/Hugs/pages/libraries/base/System-IO-Unsafe.html

unsafePerformIO

But it's a bad idea.

wheybags
  • 627
  • 4
  • 15
  • 1
    Better link is http://hackage.haskell.org/packages/archive/base/4.6.0.1/doc/html/System-IO-Unsafe.html#v:unsafePerformIO – leventov May 27 '13 at 12:56
  • 10
    It's not really a nice idea to directly give this answer. `unsafePerformIO` is a backdoor (created for for special purposes) that should not be taught to people still learning Haskell. Instead, they should learn to use Haskell in its spirit. – is7s May 27 '13 at 13:02
  • 3
    While I agree that this is not a good answer, it is still a valid one, and it was right away given with the necessary warning (though it should perhaps have explained _why_ `unsafePerformIO` is "a bad idea"). – leftaroundabout May 27 '13 at 22:45