Concat a List of Strings with additional Strings in between

Viewed 156

Here is what I'm searching for. I want to concat a given list for example:

list = [a,b,c,d]

and I want to concat those Strings. In between the concatination I want to put allways the same String so that the result looks like:

"Hey a, Hey b, Hey c, Hey d"

Is this possible in swi-Prolog?

2 Answers

You are looking for an "intersperse" or "join" function, which is hidden behind the atomic_list_concat/3 predicate:

atomic_list_concat/3

atomic_list_concat(+List, +Separator, -Atom)

or alternatively to create SWI-Prolog "strings" (which are supposed to be used in scenarios where you process text):

atomics_to_string/3

atomics_to_string(+List, +Separator, -String)

You do not only want to have "additional strings in between", since you also want something "in front" of each string. More specifically, you want "Hey " in front of each String, and ", " between each of them.

I would use maplist/3 to concat the String "Hey " in front of each of your entries using atom_concat/3.

All "Hey X"-entries can then be concatenated to a single string using atomic_list_concat/3. This predicate also takes a separator which should be placed between all entries, i.e., ", " in your case.

List = [a,b,c,d], 
maplist(atom_concat("Hey "), List, HeyList), 
atomic_list_concat(HeyList, ", ", FinalString).

Result:

List = [a, b, c, d],
HeyList = ['Hey a', 'Hey b', 'Hey c', 'Hey d'],
FinalString = 'Hey a, Hey b, Hey c, Hey d'.
Related