
28 Jan
2006
28 Jan
'06
6:52 a.m.
On 28/01/06, Andrew Savige
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