在Ocaml中动态生成具有模式匹配的函数 [英] Dynamically Generating a function with pattern matching in Ocaml

查看:56
本文介绍了在Ocaml中动态生成具有模式匹配的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数可以动态生成另一个具有动态指定模式以匹配的函数,而我对如何上手一无所知.

I am trying to write a function that dynamically generates another function with dynamically specified patterns to match, and I am very lost on how to get started.

基本上,顶级函数使用字典,其中键与值列表匹配,我想返回一个函数,该模式将那些键与值匹配.

Basically, the top-level function takes in a dictionary, where keys are matched to lists of values, and I want to return a function, that pattern matches those keys to the value.

例如,我会传入像 [("a",[1; 2; 3]);这样的字典.("b",[3])] ,我会得到一个看起来像

For example, I would pass in a dictionary like [( "a", [1;2;3]); ("b", [3])] and I would get a function that looks like

function 
| "a" -> [1;2;3] 
| "b" -> [3]

有人可以指出我的入门方向吗?

Can anyone point me in a direction on how to get started on this?

推荐答案

听起来像您想要的声音实际上只是 List.assoc ,其参数相反:

Sounds like what you want is really just List.assoc with the arguments reversed:

let f list key =
    List.assoc key list

let g =
    f [( "a", [1;2;3]); ("b", [3])]

let a = g "a" (* returns [1;2;3] *)

顺便说一句,您所谓的词典"更具体地称为关联列表.因此,该函数的名称是:)

Btw, what you call a "dictionary" is more specifically called an association list. Hence the name of the function :)

这篇关于在Ocaml中动态生成具有模式匹配的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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