[Haskell-cafe] Evaluating arithmetic expressions at run time

Andrew Savige ajsavige at yahoo.com.au
Sat Jan 28 07:37:40 EST 2006


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

/-\


Send instant messages to your online friends http://au.messenger.yahoo.com 


More information about the Haskell-Cafe mailing list