z_axis
z_axis

Reputation: 8460

How to use interpret in Language.Haskell.Interpreter?

Is interpret used to eval haskell expression ? if so, how can i use it?

Language.Haskell.Interpreter> :t interpret 
interpret :: (Data.Typeable.Internal.Typeable a, MonadInterpreter m) =>
String -> a -> m a

>interpret "1+1"
<interactive>:20:1:
Ambiguous type variable `m0' in the constraint:
  (MonadInterpreter m0) arising from a use of `interpret'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: interpret "1+1"
In an equation for `it': it = interpret "1+1"

Regards!

Upvotes: 2

Views: 988

Answers (1)

Dmytro Sirenko
Dmytro Sirenko

Reputation: 5083

There are some examples here:

interpret "head [True,False]" (as :: Bool)
interpret "head $ map show [True,False]" infer >>= flip interpret (as :: Bool)

where "Convenience functions to be used with interpret to provide witnesses":

as :: Typeable a => a   
infer :: Typeable a => a

P.S. API of Language.Haskell.Interpreter is not very user-friendly. Without inspecting its example files its usage would be a conundrum for me (not an advanced Haskeller).

But with the help of an example here we go:

Prelude> import Language.Haskell.Interpreter as I
Prelude I> runInterpreter $ setImports ["Prelude"] >> interpret "map (*2) [1,2,3]" (as :: [Int])
Right [2,4,6]

The helpful example file can be found in ~/.cabal/packages/hackage.haskell.org/hint/0.3.3.5/hint-0.3.3.5.tar.gz.

It looks like interpret must be run inside a monad constrained by MonadInterpreter m:

Prelude I> :t runInterpreter 
  runInterpreter
  :: (Functor m, Control.Monad.CatchIO.MonadCatchIO m) => 
     InterpreterT m a -> m (Either InterpreterError a)
Prelude I> :t interpret 
  interpret
  :: (Data.Typeable.Internal.Typeable a, MonadInterpreter m) => String -> a -> m a

IO clearly does not have an instance for MonadInterpreter class, hence the error. This is an expected behaviour, since IO monad of GHCI does not have required information about the interpreter session. A proper monad type must be set by runInterpreter.

Upvotes: 6

Related Questions