-
Hi, eval function expects pure value, but how to call function Trick with unsafePerformIO at first glance is working as expected, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
There are a few other solutions. First, since IO actions are ordinary values, you can use 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 can do the same with a value of type -- |
-- Execute an expression of type (IO String), and return the String.
--
-- >>> interpretIOString "mapM (\\x -> print x >> pure (chr x)) [65,66,67]"
-- 65
-- 66
-- 67
-- "ABC"
interpretIOString :: String -> IO String
interpretIOString expr = do
r <- Hint.runInterpreter $ do
Hint.setImports ["Prelude", "Data.Char"]
ioAction <- Hint.interpret expr (Hint.as :: IO String)
liftIO ioAction
case r of
Left e -> do
throwIO e
Right s -> do
pure s And if you want to support an arbitrary -- |
-- Execute an expression of type (IO a), for some type "a" which has a Show
-- instance, and return the shown result.
--
-- >>> interpretIOShow "mapM print [1,2,3]"
-- 1
-- 2
-- 3
-- "[(),(),()]"
interpretIOShow :: String -> IO String
interpretIOShow expr = do
interpretIOString ("fmap show $ " ++ expr) Finally, if you don't need to get the String back, and only want to print it like in ghci, you can use -- |
-- Like 'interpretIOShow', but print the result instead of returning it.
--
-- >>> runIOShow "mapM print [1,2,3]"
-- 1
-- 2
-- 3
-- [(),(),()]
runIOShow :: String -> IO ()
runIOShow expr = do
r <- Hint.runInterpreter $ do
Hint.setImports ["Prelude"]
Hint.runStmt expr
case r of
Left e -> do
throwIO e
Right () -> do
pure () |
Beta Was this translation helpful? Give feedback.
-
I have now enabled GitHub's "Discussions" feature on this repo, to indicate that questions like this one are welcome even though they're not bugs. |
Beta Was this translation helpful? Give feedback.
There are a few other solutions.
First, since IO actions are ordinary values, you can use
interpret
to obtain a value of typeIO ()
, and then run that IO action outside of the interpreter:You ca…