Subject: Re: [SWIPL] convert atom or term to integer

From: Jan Wielemaker <[email-masked]>
Date: Thu, 22 Mar 2001 12:11:16 +0100

>     Is there any predicate that can be used to convert atom or term into =
> integer for calculation?
> I have tried to use "int_to_atom(+Int, +Base, -Atom)" but it doesn't =
> work if I only instantiated
> the Atom part. Can anyone help? Thanks a lot!

There are many options, the best choice depends mostly on what you
want to do if the atom doesn't represent an integer and how compatible
you want to be with what.

Old prolog code uses:

	atom_to_int(Atom, Int) :-
		name(Atom, Codes),
		name(Int, Codes),
		integer(Int).

ISO code uses:

	atom_to_int(Atom, Int) :-
		atom_codes(Atom, Codes),
		number_codes(Int, Codes),
		integer(Int).

And you can also use:

	atom_to_int(Atom, Int) :-
		term_to_atom(Int, Atom),
		integer(Int).

The first case fails silently if Atom cannot be converted.  The other
two raise an exception if atom doesn't contain characters to make a
number (2nd) or atom doesn't contain valid Prolog syntax (3th) and
fail of the atom doesn't translate to an integer (atom_to_int('3.4',
X)).  See catch/3 is you want to catch the exception.

	--- Jan