Erencie
Erencie

Reputation: 441

Call a function in OCaml based on a string variable storing the function name

Is there such a mechanism in OCaml, such that I could invoke a function dynamically based on a variable storing the function name, like what I can do in other scripting languages?

For example, I have written a function foo(). And I store the String constants "foo" somewhere in a variable "x". In JavaScript I'm able to do something like this window[x](arguments); to dynamically invoke the method foo(). Can I do something similar in OCaml?

Upvotes: 1

Views: 642

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

No, this is not the kind of thing that OCaml lets you do easily. The program definition, including the names of functions and so on, isn't available for the program itself to manipulate.

A simple way to get this effect for a set of functions known ahead of time is to make a dictionary (a hash table or a map, say) of functions using the function name as the key. Note that this will require the functions to have the same type (which is a feature of OCaml not a problem :-).

Upvotes: 1

Related Questions