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

江枫思渺然 提交于 2019-12-25 05:22:54

问题


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?


回答1:


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 :-).



来源:https://stackoverflow.com/questions/22488111/call-a-function-in-ocaml-based-on-a-string-variable-storing-the-function-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!