Search code examples
haskellhint

Using Haskell to interpret multi-line strings of code at runtime


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).


Solution

  • 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"