[mercury-users] Hash_table initialization

Fergus Henderson fjh at cs.mu.OZ.AU
Wed Apr 30 11:24:13 AEST 2003


On 30-Apr-2003, Goncalo Jorge Coelho e Silva <l10454 at alunos.uevora.pt> wrote:
> 
>  I tried to used hash_tables and
> had a few problems regarding initialization.
> 
>  I am unsure whether I have to use predicates,
> where I explicitly define the default size and
> occupancy arguments, like in:
> 
> :- func new(hash_pred(K), int, float) = hash_table(K, V).

No; you can use the "new_default" function, which will use
default values for the size and occupancy arguments.
You do however have to pass to "new_default" the name of a
predicate to compute two hash values for a given key.
If the keys for your hash table are one of the builtin types
such as string, int, etc. then you can use one of the
predefined hashing predicates, e.g. string_double_hash.
Otherwise you will need to write your own.

Here's some sample code.

	:- module hash_sample.
	:- interface.
	:- import_module io.

	:- pred main(io__state::di, io__state::uo) is det.

	:- implementation.
	:- import_module hash_table.

	main(!IO) :-
		% create an empty hash table
		HashTable0 = new_default(string_double_hash),

		% insert a key and value into the hash table
		HashTable1 = det_insert(HashTable0, "some key", 42),

		% lookup a key in the hash table
		N = HashTable1^elem("some key"),

		% print the result
		print("N = ", !IO),
		print(N, !IO),
		nl(!IO).

-- 
Fergus Henderson <fjh at cs.mu.oz.au>  |  "I have always known that the pursuit
The University of Melbourne         |  of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh>  |     -- the last words of T. S. Garp.
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list