asymptote
asymptote

Reputation: 345

OCaml: Accessing a record's field with its field name as a string

Given:

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

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

Instead of doing m.foo, is it possible to access a member of the record with the field name as a string (ie. given that we only have the string "foo")?


Certainly this is possible with a map, but then all members must be the same type:

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" *)

Upvotes: 0

Views: 1112

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66803

You have captured the essence of the problem in your map comment. OCaml is strongly typed, you can't have a function whose type changes depending on a parameter. So there's no way to do what you want.

It's best to work with the OCaml type system, rather than against it. There are huge benefits once you rethink your coding techniques (in my opinion).

You can wrap different types into different variants of an algebraic type. That might work for you.

type myFooOrScore = Foo of string | Score of int

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

Upvotes: 2

Related Questions