Search code examples
ocamlcontainersrecords

Containers inside records in Ocaml


The data structure I have in mind involves a record with a member which stores unique strings. Abstractly this is the record I have in mind:

struct A {
name: string;
neighbors: Set of String;
};

But I can't seem to create a Set container inside a record in Ocaml. Given that a Set is a functor and not a traditional type, I am not sure how this can be done.


Solution

  • Set is a functor that instantiates a new type for each type of set you want; since it needs to know the comparison function, you can't do string set like you can string list (unless you use PSet, the polymorphic set, from Batteries Included or extlib). So:

    module StringSet = Set.Make(String);; (* or use BatSet.StringSet *)
    type record = {
        name: string;
        neighbors: StringSet.t;
    };
    

    With Batteries' polymorphic sets (be careful with it, as it doesn't type-check that you're using the same comparison function):

    type record = {
        name: string;
        neighbors: string BatSet.t
    };