Home > Software engineering >  Prolog: Cast term into string?
Prolog: Cast term into string?

Time:03-29

I have a Prolog program, which generates terms of this form:

:-op(803, xfy, →).

connect(X, Y, Result):-
    Result = (X → Y).

if I now call connect(a,b,R) my result is R = (a→b). Is their a possibility to convert terms like (a→b) into a string within Prolog?

Background: I want to work with the results in Python. But if I transfer it with swiplserver or pyswip I get termini of this kind: →(a, b). My hope is to solve that problem with such a typecast.

CodePudding user response:

In SWI-Prolog, you can use predicate term_string/2 as follows:

?- connect(a, b, T), term_string(T, S).
T =  (a→b),
S = "a→b". 

Alternatively, you can also use term_to_atom/2 or format/3:

?- connect(a, b, T), term_to_atom(T, A).
T =  (a→b),
A = 'a→b'.

?- connect(a, b, T), format(string(S), '~w', T).
T =  (a→b),
S = "a→b".

?- connect(a, b, T), format(atom(A), '~w', T).
T =  (a→b),
A = 'a→b'.
  • Related