user2758028
user2758028

Reputation: 31

string variable as haskell command

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

Answers (3)

qaphla
qaphla

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

cbeav
cbeav

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

Thomas M. DuBuisson
Thomas M. DuBuisson

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:

  1. Import an Interpreter module from the hint package
  2. Set a string, x, which is the expression you desire to evaluate
  3. Run the interpreter on the expression
  4. Print the result (which is already a string, so you might prefer putStrLn result).

Upvotes: 2

Related Questions