Implementing Type Classes using Type-Indexed Functions ∗

Type classes [19, 7] are, according to some authors, ‘the most beloved feature of Haskell’. They provide a clean, modular and elegant way of writing overloaded functions. Type classes are usually implemented using dictionaries—data structures containing functions and other dictionaries—which are passed as extra arguments to the overloaded functions. Thus, programs using type classes are translated into programs with dictionaries that are correct according to the DamasMilner type system. Functional logic programming (FLP) has inherited the Damas-Milner type system from its functional part, so it may seem that using the same translation for these languages is also a good option. However, this translation presents some problems in FLP because of an undesired excess of sharing that appears with non-determinism. In this paper we propose an alternative translation of type classes which uses type witnesses and type-indexed functions (in the sense of [11]) instead of dictionaries. The translated programs are correct according to a new simple extension of the Damas-Milner type system recently proposed for FLP [13]. Apart from solving the mentioned problem of undesired sharing, the proposed translation also obtains interesting efficiency results: in functional languages (GHC, Hugs) it can compete with the built-in translation, and in FLP (Toy, Curry) it obtains an important speedup—between 1.2 ∗This work has been partially supported by the Spanish projects TIN2008-06622-C03-01 and UCMBSCH-GR58/08-910502. and 2.5 in the experiments—compared to the classical translation.