1

I am struggling to identify a way to convert a list to string. This list is the output from a findall predicate.

see below my code.

edge(a,b).
edge(a,c).
edge(b,c).
edge(c,d).
edge(c,e).
edge(d,e).
edge(f,g).
edge(g,h).

route(X, Z, [])    :-  edge(X, Z).
route(X, Z, [Y|T]) :-  edge(X, Y), route(Y, Z, T).

allways(X, Y) :- findall(E, (route(X, Y, E), write(E), nl), _).
%allways(X, Y) :- findall(E, (route(X, Y, E), with_output_to(atom(_),maplist(write, E)), nl), _).
%allways(X, Y) :- findall(E, (route(X, Y, E), atomic_list_concat(E,'',A), nl), _),write(A).

my output

?- allways(a,e).
[b,c]
[b,c,d]
[c]
[c,d]

expected output

?- allways(a,e).
bc
bcd
c
cd

I tried different ways to convert the list to string using with_output_to predicate and atomic_list_concat predicate but nothing works.

false
  • 10,264
  • 13
  • 101
  • 209
mkpisk
  • 152
  • 1
  • 9

1 Answers1

1

When you say "string", what do you mean?

There are many predicates for concatenating a list to an atom. In your case atomic_list_concat/2 sounds about right.

Your problem however is in how you wrote the findall, you are capturing the wrong variable.

?- findall(Str, ( route(a, e, E), atomic_list_concat(E, Str) ), Strs),
   forall(member(Str, Strs), format("~w~n", [Str])).

or, if you do not need the list at all, do not use findall at all.

?- forall(( route(a, e, E),
            atomic_list_concat(E, Str)
          ),
          format("~w~n", [Str])).
TA_intern
  • 2,222
  • 4
  • 12
  • your understanding of the string seem is ok (without the comma) to me. But i wanted to output 'Str' rather than the 'Strs' from your code. I modified your suggestion but it is not working. ``` findall(E, (route(X, Y, E), atomic_list_concat(E,write(Str))), Strs) ``` – mkpisk Oct 12 '20 at 10:56
  • @mkpisk The `write` should **not** be inside the findall, this is for certain. Take my code exactly as is, and _after_ the findall do the writing. And do not put code in comments. – TA_intern Oct 12 '20 at 10:59
  • It is not working if I write(Str) outside by giving a , (AND condition) to findall. – mkpisk Oct 12 '20 at 11:07
  • @mkpisk there are (countably?) infinite ways to make something that is not working. See my edited answer. – TA_intern Oct 12 '20 at 11:08
  • awesome. It is a new trick to use forall and the way you wrote format. Thank you very much for teaching :) – mkpisk Oct 12 '20 at 11:13