Guarded Methods in OCaml
4 hours ago
- Guarded methods attach constraints to the receiver only for specific methods, allowing calls only when the receiver satisfies those constraints.
- OCaml does not natively support guarded methods, but they can be encoded using a type equality witness.
- The problem arises when a class-level generic constraint is too broad; method-level constraints are more flexible.
- Three approaches exist: moving the method outside the class, extension methods, and guarded methods, with the last being most ideological.
- The encoding uses a custom eq type with Refl constructor to represent type equalities.
- For example, a flatten method on a list of lists requires a witness ('a, 'b list) eq.
- A sum method can be constrained to int using ('a, int) eq.
- Applying a guarded method with an incompatible type results in a compile-time error, ensuring type safety.
- While the encoding is verbose, it demonstrates a practical use of equality witnesses and preserves message-passing semantics.