Reputation: 31
when I do following it works
print [1..5]
and result [1,2,3,4,5]
but why following is not working
let x = "[1..5]"
print x
I want to process a string variable as haskell command. can someone please help me in it.
Upvotes: 2
Views: 1299
Reputation: 4733
It looks like you're looking for System.Eval.Haskell.eval
or one of its variants. In this case, I believe that
import System.Eval.Haskell
do x <- eval "[1..5]" [] :: IO (Maybe Int List)
putStrLn (if isJust x then "" else show $ fromJust x)
will do what you want.
Upvotes: 0
Reputation: 11
If you just want to get a list as a string, take advantage of the show function
let x = show [1..5]
print x
Your first answer "works" because function application is right associative, so Haskell evaluates [1..5] to produce the list [1,2,3,4,5] and passes this to the print function.
Upvotes: 1
Reputation: 64740
Note that your second example:
let x = "[1..5]"
print x
works just fine, it just says something different than you intended.
If you wish to consider some string as a valid Haskell expression then you'll need to interpret that string via some Haskell interpreter. The most common interpreter is accessed via the ghc-api. A clean wrapper for the ghc-api is the hint
package.
A simple example of using hint is (via ghci):
import Language.Haskell.Interpreter
let x = "[1..5]"
Right result <- runInterpreter $ setImports ["Prelude"] >> eval x
print result
The above code will:
hint
packagex
, which is the expression you desire to evaluateputStrLn result
).Upvotes: 2