I'm trying to add a special character (*) to every element of a list.
I want to add it in the beginning and the end of the element, so if I have:
list(apple,orange,pear)
It would be:
list(*apple*,*orange*,*pear*)
Is there a way to do that in prolog?
Thank you.
CodePudding user response:
To concatenate two atoms, you can use the ISO predicate atom_concat/3:
?- atom_concat('*', apple, StarAtom), atom_concat(StarAtom, '*', StarAtomStar).
StarAtom = '*apple',
StarAtomStar = '*apple*'.
Using this predicate, you can define the following new predicate:
% starry_atom( Atom, -StarAtomStar)
starry_atom(Atom, StarAtomStar) :-
atom_concat('*', Atom, StarAtom),
atom_concat(StarAtom, '*', StarAtomStar).
Example:
?- starry_atom(apple, StarryAtom).
StarryAtom = '*apple*'.
To apply starry_atom/2
to all elements of a list, supposing that all elements of the list are atoms, you can use the predicate maplist/3.
?- maplist(starry_atom, [apple, orange, pear], List).
List = ['*apple*', '*orange*', '*pear*'].
NOTE In SWI-Prolog, you can also use the predicate atomic_list_concat/2.
?- atomic_list_concat(['*', apple, '*'], Atom).
Atom = '*apple*'.