[mercury-users] newbie question: instantiating a type (practicing with the tutorial)

Raphael Collet rco at missioncriticalit.com
Thu Sep 23 19:55:08 AEST 2010

Dear Jean-Marc,

On 09/23/2010 11:28 AM, Jean-Marc Vanel wrote:
> Thanks Tomas
> It works like this.
> This is very useful to use the map library like you showed, but my
> original question was related to the example in the (one and only:( )
> Mercury tutorial in paragraph 2. 7 :
> http://www.mercury.csse.unimelb.edu.au/information/papers/book.pdf
> :- module dictionary.
> :- interface.
> :- type dictionary(Key, Value).
> :- pred search(dictionary(Key, Value)::in, Key::in, Value::out) is semidet.
> :- func set(dictionary(Key, Value), Key, Value) = dictionary(Key, Value).
> :- implementation.
> :- import_module list.
> :- type dictionary(Key, Value) == list({Key, Value}).
> search([{K, V} | Dict], Key, Value) :-
> ( if Key = K then Value = V else search(Dict, Key, Value) ).
> set(Dict, Key, Value) = [{Key, Value} | Dict].
> I tried to make use of this module (admitedly not computationally
> efficient but that's not the point).
> Can I use this module like is is , or is some init predicate necessary ?

If you don't provide an init predicate or function, the user of the 
module has no way to create an empty dictionary.  As such, this module 
is useless...  Therefore you have to provide one.

One convention we regularly use is a polymorphic init function like

:- func init = dictionary(Key, Value).
init = [].

You can usually call it without specifying the actual type parameters. 
In the following example, the compiler will be able to infer the type 
dictionary(string, string) with the second statement.

	Dic1 = init,
	Dic2 = set(Dic1, "foo", "bar"),

In case the compiler is unable to infer the actual type, you can help it 
by explicitly adding a type constraint:

	Dic1 = init : dictionary(string, string),

This is sometimes required when the context does not allow the compiler 
to make this inference.

I hope this will help you.

Kind regards,

Raphael Collet
Mission Critical IT
mercury-users mailing list
Post messages to:       mercury-users at csse.unimelb.edu.au
Administrative Queries: owner-mercury-users at csse.unimelb.edu.au
Subscriptions:          mercury-users-request at csse.unimelb.edu.au

More information about the users mailing list