From jan@swi.psy.uva.nl Thu Mar 22 12:11:16 2001
Received: from gollem.swi.psy.uva.nl (root@gollem [145.18.152.30])
	by swi.psy.uva.nl (8.11.2/8.11.2) with ESMTP id f2MBBG313703;
	Thu, 22 Mar 2001 12:11:16 +0100 (MET)
Received: (from jan@localhost)
	by gollem.swi.psy.uva.nl (8.11.2/8.11.2/SuSE Linux 8.11.1-0.5) id f2MBBGA21568;
	Thu, 22 Mar 2001 12:11:16 +0100
Date: Thu, 22 Mar 2001 12:11:16 +0100
Message-Id: <200103221111.f2MBBGA21568@gollem.swi.psy.uva.nl>
From: Jan Wielemaker <jan@swi.psy.uva.nl>
Subject: Re: [SWIPL] convert atom or term to integer
To: Cecilia Wong <50000481@plink.cityu.edu.hk>, prolog@swi.psy.uva.nl
In-Reply-To: Cecilia Wong's message of Thu, 22 Mar 2001 18:58:50 +0800
Phone: +31 - 20 - 525 6121

>     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

