How to define your own polymorfic type in Mercury

Fergus Henderson fjh at
Sat Apr 10 19:29:36 AEST 1999

On 09-Apr-1999, Henk Vandecasteele <Henk.Vandecasteele at> wrote:
> Dear mercury-users(
> I have the following interface of a mutable object:
> :- module mutable.
> :- interface.
> :- type mutable(T). /* a polymorfic mutable object */
> :- pred mutable__init(mutable(T), T).
> :- mode mutable__init(out, in) is det.
>      /* create a new mutable object with the initial contents */
> :- pred mutable__overwrite(mutable(T), T).
> :- mode mutable__overwrite(in, in) is det.
>      /* Overwrite the current contents of the mutable object with 
>         a new data. When the system backtracks over  this operation
>         the old data willl be restored  */

Those two predicates should be declared `impure'.

	:- impure pred mutable__init(mutable(T), T).
	:- impure pred mutable__overwrite(mutable(T), T).

If you don't do that, the compiler might (depending on the exact
compilation options) optimize away calls to them.

> :- pred mutable__get(mutable(T), T).
> :- mode mutable__get(in, out) is det.
>     /* Get the current contents of the mutable object */

That one should be declared `semipure', for the same reason.

	:- semipure pred mutable__get(mutable(T), T).

> I had an implementation which is based on the array-module in 
> the library. I do not understand half wat happened in there,
> I suppose this is not the way to do it. I added the code in the end 
> of the mail. It worked up to version 0.8, but it fails
> with "rotd-1999-04-04". Of course I could again see what happened 
> with array.m (of course I already did) and mimic it again.
> But is there I better documented way? I searched without luck.

In general, the way to declare a type which is actually implemented
in C is to use the `c_pointer' type, e.g.

	:- type mutable(T) ---> mutable(c_pointer).

But in this particular case, there is already a library in the
mercury-extras distribution which does exactly the same thing
as your `mutable' module.  See extras/references/reference.m.

Fergus Henderson <fjh at>  |  "I have always known that the pursuit
WWW: <>  |  of excellence is a lethal habit"
PGP: finger fjh at        |     -- the last words of T. S. Garp.

More information about the users mailing list