根据存储函数名称的字符串变量在 OCaml 中调用函数 [英] Call a function in OCaml based on a string variable storing the function name

查看:60
本文介绍了根据存储函数名称的字符串变量在 OCaml 中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OCaml 中是否有这样的机制,以便我可以根据存储函数名称的变量动态调用函数,就像我在其他脚本语言中可以做的那样?

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?

例如,我写了一个函数 foo().我将字符串常量foo"存储在变量x"中的某处.在 JavaScript 中,我可以像这样 window[x](arguments); 来动态调用方法 foo().我可以在 OCaml 中做类似的事情吗?

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?

推荐答案

不,这不是 OCaml 让您轻松完成的事情.程序定义,包括函数名称等,是程序本身无法操作的.

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.

为一组提前已知的函数获得这种效果的一种简单方法是使用函数名称作为键制作函数的字典(比如哈希表或映射).请注意,这将要求函数具有相同的类型(这是 OCaml 的一个特性,不是问题:-).

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

这篇关于根据存储函数名称的字符串变量在 OCaml 中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆