Reputation: 23
I am trying to concatenate 4 strings in Prolog. I am able to concatenate 2 and 3 strings but I can't get it to work with 4. This is what I have so far:
join2(String1,String2,Newstring) :-
name(String1,L1), name(String2,L2),
append(L1,L2,Newlist),
name(Newstring,Newlist).
join3(String1,String2,String3,Newstring) :-
join2(String1,String2,S),
join2(S,String3,Newstring).
join4(String1,String2,String3,String4,Newstring) :-
join3(String1,String2,String3,Newstring),
join2(String1,String2,S),
join2(S,String3,Newstring).
join3(Newstring,String4,Newstring).
Upvotes: 2
Views: 2069
Reputation: 58244
I'm not sure what your constraints are, but you can also use SWI's append/2
and maplist/3
:
concatenate(StringList, StringResult) :-
maplist(atom_chars, StringList, Lists),
append(Lists, List),
atom_chars(StringResult, List).
Then you can concatenate as many as you like:
?- concatenate(["hello", ", ", "world"], String).
String = 'hello, world'.
?- concatenate(["hey, ", "you ", "don't ", "say!"], String).
String = 'hey, you don\'t say!'.
?-
Note that the above assumes you are using the default setting in SWI Prolog:
:- set_prolog_flag(double_quotes,atom).
where "abc"
represents a Prolog atom and is equivalent to 'abc'
.
Upvotes: 2
Reputation: 49803
You'll need at least 2 intermediate NewStrings in order to join 4 strings, but your proposed solution only uses 1 (S
), although it tries to use NewString
as both an intermediate and the final result.
Take what you did for join3
a step further:
join4(S1,S2,S3,S4,NS) :-
join2(S1,S2,NS12),
join2(S3,S4,NS34),
join2(NS12,NS34,NS).
Upvotes: 1