简体   繁体   中英

How to concatenate a string to multiple elements in a list via Prolog?

I'm new to prolog and have been working on a problem related to what I believe is concatenation functionality in prolog. After reading the documentation for predicates that work on lists and strings, I am left with more questions than answers.

The goal I'm trying to achieve is to create one single product from distributing a string across all the different elements in a list. I've used append/2 and maplist/2 and some other predicates but have always gotten a response of false. Example of what I'm trying to achieve:

?- cellprod("B",["C","D","E"],X).
X = ["BC", "BD", "BE"].

Current code:

cellprod(A,[B|B1],C):- append(A,B),
                       cellprod(A,B1,C).

What predicates should I be looking at for a string to list conversion to distribute and end with a newly formed list? Or is there a concatenation predicate I am missing? Much appreciated!

Maybe you are required to learn about recursion, so this answer could be totally useless... anyway... we can solve easily in this way:

?- S="B",L=["C","D","E"],findall(T,(member(E,L),string_concat(S,E,T)),X).
S = "B",
L = ["C", "D", "E"],
X = ["BC", "BD", "BE"].

or this:

?- S="B",L=["C","D","E"],maplist(string_concat(S),L,X).
S = "B",
L = ["C", "D", "E"],
X = ["BC", "BD", "BE"].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM