Choosing a function by (string) name...

Hi, Suppose I have a module of functions with identical signatures: module Functions where a :: Int -> [Int] a x = [x + 1, x + 2, x + 3] b :: Int -> [Int] b x = [x + 4, x + 5, x + 6] and in my main function I receive a command line arguments (a string) naming one of the functions in MyModule. I'd like to lookup and use of the functions by name: lookup :: String -> (Int -> [Int]) lookup "a" = MyModule.a lookup "b" = MyModule.b ... Is there a more idiomatic Haskell way of going about this? I can see there's a fundamental tension between a runtime choice of function name expressed as a string and the need for compile-time known function choice. Thanks, Stu

On Sun, May 20, 2012 at 8:28 AM, Stuart Hungerford
Hi,
Suppose I have a module of functions with identical signatures:
module Functions where
a :: Int -> [Int]
a x = [x + 1, x + 2, x + 3]
b :: Int -> [Int]
b x = [x + 4, x + 5, x + 6]
and in my main function I receive a command line arguments (a string) naming one of the functions in MyModule. I'd like to lookup and use of the functions by name:
lookup :: String -> (Int -> [Int])
lookup "a" = MyModule.a
lookup "b" = MyModule.b
...
Is there a more idiomatic Haskell way of going about this? I can see there's a fundamental tension between a runtime choice of function name expressed as a string and the need for compile-time known function choice.
Since the two functions have the same type there is no problem to do this, and in fact you have already hinted at a reasonable solution yourself: create an assoctiation list and use lookup (http://is.gd/wZPlNJ). /M -- Magnus Therning OpenPGP: 0xAB4DFBA4 email: magnus@therning.org jabber: magnus@therning.org twitter: magthe http://therning.org/magnus

On Sun, May 20, 2012 at 5:51 PM, Magnus Therning
[...] Since the two functions have the same type there is no problem to do this, and in fact you have already hinted at a reasonable solution yourself: create an assoctiation list and use lookup (http://is.gd/wZPlNJ).
Thanks Magnus, that's a clear and simple approach. Stu
participants (2)
-
Magnus Therning
-
Stuart Hungerford