Iqazra
Iqazra

Reputation: 419

Getting the list of ASCII values from term in Prolog

I am using SWI-Prolog version 7.6.3 and I recently encounter a problem for converting a term that combines number and alphabet into its list of ASCII values.

I know that we can obtain the list of ASCII values of a particular term using name/2 predicate. For example, if I want to get the ASCII value of the term ab or 'ab', then we can use name(ab,X). Prolog simply outputs X = [97, 98], 97 and 98 are respectively the ASCII values of a and b.

The predicate name/2 also works for numbers. If I want to get the ASCII values of the term 123 or '123', then we can use name(123,X). Again, Prolog simply outputs X = [49, 50, 51] where 49, 50, and 51 are correspondingly the ASCII values of 1, 2, and 3.

However, the predicate name/2 does not work if I combine number and alphabet in one term. For example, I expect that name(2a,X) returns X = [49, 97] and name(3b,X) returns X = [50,98]. However, the interpreter gives the error exception saying that an operator is expected.

I notice that the problem only occurs if the term begin with number. I check in the interpreter that name(a2,X) returns X = [97, 49] as expected.

How do I solve this problem? Or this condition inherently cannot be handled in Prolog?

Upvotes: 3

Views: 1077

Answers (1)

mat
mat

Reputation: 40768

3a is not a Prolog atom. To make it an atom, write it in single quotes:

'3a'

Also, check out atom_chars/2 to relate atoms to lists of characters!

Upvotes: 5

Related Questions