[mercury-users] An enumeration as a type: how to do it?

Andrew Bromage bromage at cs.mu.OZ.AU
Sun May 24 09:18:39 AEST 1998

G'day all.

Ann Tecklenburg wrote:

> How do I do an enumerated type?  Something like in standard Prolog:
> integraltype(T):- member(T, ['byte', 'short', 'int', 'long', 'char']).
> %I need for byte, short, int, long, char, etc to be strings not Mercury
> %datatypes.

In Mercury, strings are strings and atoms are atoms, and never the twain
shall meet... unless you convert them.  Here are no less than three ways
to manage things, depending on the amount of generality that you need.

:- type integral_type
	--->	byte
	;	short
	;	int
	;	long
	;	char.

:- pred int_type_to_string(integral_type, string).
:- mode int_type_to_string(in, out) is det.
:- mode int_type_to_string(out, in) is semidet.

int_type_to_string(byte, "byte").
int_type_to_string(short, "short").
int_type_to_string(int, "int").
int_type_to_string(long, "long").
int_type_to_string(char, "char").

The two modes of int_type_to_string/2 give you a simple mechanism for
converting backwards and forwards between integral_type and string.

If you're only planning to convert in one direction, using a function may
be a little syntactically cleaner:

:- func name_int_type(integral_type) = string.

name_int_type(byte) = "byte".
name_int_type(short) = "short".
name_int_type(int) = "int".
name_int_type(long) = "long".
name_int_type(char) = "char".

So you can say, for example:

	string__append_list([name_int_type(Type), " ", VarName], Decl)

as opposed to:

	int_type_to_string(Type, TypeName),
	string__append_list([TypeName, " ", VarName], Decl)

Naturally, you can use two functions if you want to (to convert both ways)
but a) it takes up space and b) you have a (small but present) double
maintenance problem.

Last but not least, if all you're planning to do with the final string
is write it to some output stream, you don't have to convert at all.
Simply call io__write/{3,4} with the appropriate integral_type and it
will all happen for you.

Hope this helps.

Andrew Bromage

More information about the users mailing list