There is function in python called eval
that takes string input and evaluates it.
>>> x = 1
>>> print eval('x+1')
2
>>> print eval('12 + 32')
44
>>>
What is Haskell equivalent of eval
function?
eval provides a typesafe (to a limit) form of runtime evaluation for Haskell -- a limited form of runtime metaprogramming. The String argument to eval is a Haskell source fragment to evaluate at rutime. imps are a list of module names to use in the context of the compiled value.
The asteval package evaluates mathematical expressions and statements, providing a safer alternative to Python's builtin eval() and a richer, easier to use alternative to ast. literal_eval() . It does this by building an embedded interpreter for a subset of the Python language using Python's ast module.
Python's eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you're trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.
This question is asked 11 years ago, and now use the package hint
we can define eval
very easily, following is an example as self-contained script (you still need nix to run it)
#!/usr/bin/env nix-shell
#! nix-shell -p "haskellPackages.ghcWithPackages (p: with p; [hint])"
#! nix-shell -i "ghci -ignore-dot-ghci -fdefer-type-errors -XTypeApplications"
{-# LANGUAGE ScopedTypeVariables, TypeApplications, PartialTypeSignatures #-}
import Data.Typeable (Typeable)
import qualified Language.Haskell.Interpreter as Hint
-- DOC: https://www.stackage.org/lts-18.18/package/hint-0.9.0.4
eval :: forall t. Typeable t => String -> IO t
eval s = do
mr <- Hint.runInterpreter $ do
Hint.setImports ["Prelude"]
Hint.interpret s (Hint.as :: t)
case mr of
Left err -> error (show err)
Right r -> pure r
-- * Interpret expressions into values:
e1 = eval @Int "1 + 1 :: Int"
e2 = eval @String "\"hello eval\""
-- * Send values from your compiled program to your interpreted program by interpreting a function:
e3 = do
f <- eval @(Int -> [Int]) "\\x -> [1..x]"
pure (f 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With