OCaml:访问记录';字段名为字符串的s字段

OCaml:访问记录';字段名为字符串的s字段,ocaml,Ocaml,鉴于: 不执行m.foo,是否可以访问字段名为字符串的记录成员(即,假设我们只有字符串“foo”) 当然,这在映射中是可能的,但是所有成员必须是相同的类型: type thing = {foo: string; score: int; };; (* possibly more fields... *) let m = {foo = "Bar"; score = 1; };; Printf.printf "%s\n" m.foo;; (*=> "Bar" *) 您已经在地图注释中抓住了

鉴于:

不执行
m.foo
,是否可以访问字段名为字符串的记录成员(即,假设我们只有字符串
“foo”


当然,这在映射中是可能的,但是所有成员必须是相同的类型:

type thing = {foo: string; score: int; };; (* possibly more fields... *)
let m = {foo = "Bar"; score = 1; };;

Printf.printf "%s\n" m.foo;; (*=> "Bar" *)

您已经在地图注释中抓住了问题的本质。OCaml是强类型的,不能有类型随参数变化的函数。所以没有办法做你想做的事

最好使用OCaml类型的系统,而不是反对它。在我看来,一旦你重新思考你的编码技术,就会有巨大的好处

可以将不同的类型包装为代数类型的不同变体。那可能对你有用

module Thing = Map.Make(String);;
let m = Thing.empty;;
let m = Thing.add "foo" "Bar" m;;
let m = Thing.add "score" "1" m;; (* must all be same type *)

Printf.printf "%s\n" (Thing.find "foo" m);; (*=> "Bar" *)

不,我不这么认为<代码>类型thing={foo:string;score:int;}是一条记录。我不认为你可以通过一个字符串来引用里面的标签。这是当你的大脑被过度反射感染时会发生的事情。
type myFooOrScore = Foo of string | Score of int

let field r = function
| "foo" -> Foo r.foo
| "score" -> Score r.score
| _ -> raise Not_found