[m-users.] Document "Module typeclasses should be instantiated in the interface"

Peter Wang novalazy at gmail.com
Fri May 14 11:24:38 AEST 2021


On Thu, 13 May 2021 08:11:04 +0200 fabrice nicol <fabrnicol at gmail.com> wrote:
>     %------------------------------------------------------------------------%
> 
>     :- module mod2.
>     :- interface.
>     :- import_module string.
> 
>     :- typeclass eval_type(T) where [
>          pred eval(T),
>          mode eval(out) is det
>     ].
> 
>     % :- instance eval_type(string).
> 
>     :- pred eval_string(string::out) is det.
> 
>     :- implementation.
> 
>     :- instance eval_type(string) where [
>          pred(eval/1) is eval_string
>     ].
> 
>     eval_string(Result) :- Result = "a".
> 
>     %------------------------------------------------------------------------%
> 
>     :- module test2.
>     :- interface.
>     :- import_module io.
>     :- pred main(io::di, io::uo) is det.
> 
>     :- implementation.
> 
>     :- import_module string, list.
>     :- import_module mod2.
> 
>     main(!IO) :-
>          eval(S11),
>          io.format("this string: %s\n", [s(S11)], !IO),
>          io.nl(!IO).
> 
> %------------------------------------------------------------------------%
> 
> The error message on building test2 disappears if library mod2 is 
> rebuilt **after uncommenting** the abstract instance declaration in the 
> interface.
> 
> Why there should be an abstract instance declaration in the interface of 
> the module may be understood.
> 
> What is odd is that mod2 builds into a library whether the abstract 
> instance declaration is present or not in the interface.

This works as intended. mod2 declares that 'string' is an instance of
the 'eval_type' typeclass, but the instance declaration occurs in the
implementation section of the module so is not visible to any module
that imports mod2. That's why you get an unsatisfiable typeclass
constraint error when compiling test2.

By adding the abstract instance declaration to the interface section,
that information is passed onto modules that import mod2.

Peter


More information about the users mailing list