Skip to content

How to evaluate an IO function? #122

Answered by gelisam
yaitskov asked this question in Q&A
Discussion options

You must be logged in to vote

There are a few other solutions.

First, since IO actions are ordinary values, you can use interpret to obtain a value of type IO (), and then run that IO action outside of the interpreter:

import Control.Exception (throwIO)
import Control.Monad.IO.Class (liftIO)
import qualified Language.Haskell.Interpreter as Hint

-- |
-- Execute an expression of type IO ()
--
-- >>> interpretIO "mapM_ print [1,2,3]"
-- 1
-- 2
-- 3
interpretIO :: String -> IO ()
interpretIO expr = do
  r <- Hint.runInterpreter $ do
    Hint.setImports ["Prelude"]
    ioAction <- Hint.interpret expr (Hint.as :: IO ())
    liftIO ioAction
  case r of
    Left e -> do
      throwIO e
    Right () -> do
      pure ()

You ca…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by yaitskov
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #120 on April 11, 2021 18:58.