borngold
borngold

Reputation: 69

How to convert a list to a string in Prolog?

I have a list L =[a+b,b+c] and I want to convert it to a string and print the output a+bb+c.

Can you please help me convert this list to a string? I tried using atomic_list_concat in SWI-Prolog but it gave a type error for a+b.

Upvotes: 1

Views: 4632

Answers (2)

Kaarel
Kaarel

Reputation: 10672

In SWI-Prolog:

?- with_output_to(atom(Atom), maplist(write, [a+b, b+c])).
Atom = 'a+bb+c'.

You can replace write with a call to a custom predicate if you need more control over how your terms (e.g. a+b) are written.

Upvotes: 3

Eusebius
Eusebius

Reputation: 531

The members of your list are compound terms, so you have to make them atomic before calling atomic_list_concat:

custom_print(L) :-
  maplist(term_to_atom, L, L1),
  atomic_list_concat(L1, L2),
  print(L2).

Upvotes: 1

Related Questions