Skip to content
Tech News
← Back to articles

Guarded Methods in OCaml

read original more articles

Guarded methods allow attaching constraints to the receiver ( self ) only for certain methods , thus allowing these methods to be called only if the receiver satisfies these constraints (these guards). OCaml does not syntactically allow defining this kind of method directly. In this note, we will see how to encode them using a type equality witness .

Guarded methods make it possible to attach constraints to the receiver ( self ) only for certain methods, meaning these methods can only be called if the receiver satisfies those constraints (these guards). OCaml does not, syntactically, allow defining this kind of method directly. In this note, we’ll look at how to encode them using a type equality witness.

Problem presentation

When a language (where type checking is done before the program runs, like in Java or OCaml) introduces parametric polymorphism (Java's generics), it's sometimes possible to constrain type variables. For example:

class MyClass <T extends S > { . . . }

We make MyClass generic by assuming that the type variable T is a subtype of S . The problem is that the constraint applies to the entire class. Yet sometimes, we’d like to have constraints apply only to certain methods. For example, let’s say we have a class MyList describing a list:

class MyList <A> extends ArrayList< A > { public int length ( ) { return this . size ( ) ; } }

How can we define a flatten method that, for a list like [[1, 2, 3], [4, 5]] , would produce the list [1, 2, 3, 4, 5] ? If we place the constraint at the class level, we force our list to be "always a list of lists," which is very limiting. To implement such a method, we have three theoretical approaches available.

Moving the method outside the class

The first solution is the most obvious: simply "cheat" by moving the method outside the class body (for example, into the static context or a companion object):

... continue reading