Search code examples
prologswi-prolog

Concat a List of Strings with additional Strings in between


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?


Solution

  • 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'.