3

Problem:

I would like to be able to interpret any sort of Haskell code at runtime - also code that is not bound by a single line.

Right now I am using hint to do this below, which works with single lines:

html :: String -> IO String
html code = do    
    r <- runInterpreter $ do
        setImports ["Prelude"]
        interpret code (as :: () -> String)

    case r of
        Left err -> return $ show err
        Right func -> return $ func()

Example:

If code from above is \() -> "Hello World" that works.

But if code is something like this below, my code from above does not work: (Update: it does).

\() -> let concatString :: String -> String -> String
           concatString str1 str2 = str1 ++ str2
       in concatString "Hello" "World"

Question:

How do I interpret multi-line Haskell strings at runtime using hint or any other library?


Update

This does work - I made a mistake in the original expression (which I have now corrected).

1 Answer 1

3

I haven't used hint, but I can tell you that your example is not a valid Haskell expression. where clauses are not attached to expressions, they are attached to definitions. That is, you have to have an = sign to be able to have a where clause.

-- Correct
foo = bar
    where
    bar = baz
        where 
        baz = 42

-- Incorrect
foo = (bar + 1 where bar = 41)

If you want to define something in expression context you must use let

let concatString :: String -> String -> String
    concatString str1 str2 = str1 ++ str2
in concatString "Hello" "World"
Sign up to request clarification or add additional context in comments.

2 Comments

You're right! And that was also the issue, using the let statement works, also with multi-lines. Amazing! Is there no way to attach definitions to expressions in Haskell?
There is, and it's let. let : expression :: where : definition. You can even put a where clause after a definition you make in let (I think)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.