[Haskell-beginners] Choosing a function by (string) name...

Magnus Therning magnus at therning.org
Sun May 20 09:51:15 CEST 2012


On Sun, May 20, 2012 at 8:28 AM, Stuart Hungerford
<stuart.hungerford at gmail.com> wrote:
> 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 at therning.org   jabber: magnus at therning.org
twitter: magthe               http://therning.org/magnus



More information about the Beginners mailing list