[Haskell-cafe] Evaluating arithmetic expressions at run time

Sebastian Sylvan sebastian.sylvan at gmail.com
Sat Jan 28 08:30:23 EST 2006


On 1/28/06, Andrew Savige <ajsavige at yahoo.com.au> wrote:
> --- Brian Hulley wrote:
> >> def myeval(x, y, op)
> >>   x.send op, y
> >> end
> >
> > This could be done in Haskell by
> >
> > myeval :: a->b->(a -> b -> c) -> c
> > myeval x y op = op x y
> >
> > eg myeval (+) 1 2
>
> Though the following program does indeed work:
>
> myeval :: (Int -> Int -> Int) -> Int -> Int -> Int
> myeval op x y = op x y
>
> main :: IO ()
> main = do putStrLn $ show (myeval (+) 2 3)
>
> I can't hardwire (+) because the operator is unknown at
> compile time; it is input to the program at run time as
> a string ("+" in this example).
>
> My problem is how to convert the string "+" to the operator
> (+) at run time. Well, I could do it with a lookup table:
>
> mycvt :: String -> (Int -> Int -> Int)
> mycvt "+" = (+)
> mycvt "-" = (-)
> mycvt "*" = (*)
>
> but that is what I'm trying to avoid (I was naively hoping
> that the read function could magically do it somehow :-).
>

It's probably a bit more heavy-weight than what you were looking for,
but take a look at:
http://www.cse.unsw.edu.au/~dons/hs-plugins/

It allows you to load and execute Haskell code at run-time. I suppose
this should also be possible by importing some part of GHC (perhaps
GHCi).

/S

--
Sebastian Sylvan
+46(0)736-818655
UIN: 44640862


More information about the Haskell-Cafe mailing list