[Haskell-cafe] Closed type classes [was: Exporting a Type Class for Type Signatures]

oleg at okmij.org oleg at okmij.org
Tue Nov 11 01:21:55 EST 2008

Dominic Steinitz wrote:
> In the crypto package, I have two functions
> > encrypt :: AESKey a => a -> Word128 -> Word128
> > decrypt :: AESKey a => a -> Word128 -> Word128

but the class AESKey is not exported, to prevent the user from adding
more instances to it. Since AESKey is not exported, the users cannot
write signatures that mention that class constraint. The question is,
how to export a _closed_ class -- a class the user cannot extend.

Chung-chieh Shan and I had a similar problem in our TFP2007 paper: the
classes that implement type-level arithmetic must be closed, to
prevent the user from declaring that 1+1=1. It seems the best method
is to use class aliases:

In the implementation of AES, introduce

	class AESKey a => AESKeyExport a
	instance AESKey a => AESKeyExport a -- the only instance

and now export AESKeyExport (but leave AESKey hidden). If the user
needs to write the signature for their function:

foo :: AESKeyExport a => a -> Word128 -> Word128
foo x y = encrypt x y

they should use the constraint AESKeyExport a. That constraint entails 
AESKey a, which they cannot mention. The users can try to extend the
class ESKeyExport a, but that would do them no good: the library uses
the instances of AESKey rather than AESKeyExport.

The TFP2007 paper explains that in a bit more detail:
(Section 2.1). It also mentions a different method, relying on partial
type signatures.

More information about the Haskell-Cafe mailing list