[Haskell-cafe] Evaluating arithmetic expressions at run time

Cale Gibbard cgibbard at gmail.com
Sat Jan 28 01:52:19 EST 2006


On 28/01/06, Andrew Savige <ajsavige at yahoo.com.au> wrote:
> Haskell beginner using GHC.
>
> I have a function to do some simple arithmetic at run time:
>
> myeval :: Int -> Int -> String -> Int
> myeval x y "+" = (+) x y
> myeval x y "-" = (-) x y
> myeval x y "*" = (*) x y
> -- ...
>
> While that works, I'm curious to know if it can be done more
> elegantly. I'm thinking of something like:
>
> myeval :: Int -> Int -> String -> Int
> myeval x y op = (read op) x y
>
> Thanks,
> /-\

Apart from moving to a lookup Map or something, a simple reordering of
the arguments allows you to shorten things up a bit:

myeval :: String -> Int -> Int -> Int
myeval "+" = (+)
myeval "-" = (-)
myeval "*" = (*)
etc.

- Cale


More information about the Haskell-Cafe mailing list