Prolog string manipulation
I have a string like 'pen,pencil,eraser'
. How can I make this predicate.
things(pen,pencil,eraser).
Do you have any idea? 开发者_如何学JAVA( I use prolog)
Here's a small example of specialized Prolog code for your problem which should work on most implementations (not only SWI-Prolog, but GNU Prolog, SICStus, etc.):
make_term(Functor, StringArgs, Term) :-
split_atom(StringArgs, ',', Args),
Term =.. [Functor|Args].
split_atom(A, E, L) :-
atom_chars(A, C),
split_atom2(C, E, L).
split_atom2([], _, []).
split_atom2(C, E, [A|L]) :-
append(C0, [E|C1], C), !,
atom_chars(A, C0),
split_atom2(C1, E, L).
split_atom2(C, _, [A]) :-
atom_chars(A, C).
Testing it out:
?- make_term(things, 'pen,pencil,eraser', T).
T = things(pen, pencil, eraser).
if you use swi-prolog, you can create this first: 'things(pen,pencil,eraser)' and then use term_to_atom/2
so something like:
get_term(Term):-
atom_concat('things(','pen,pencil,eraser',Temp),
atom_concat(Temp,')',A),
term_to_atom(Term, A).
精彩评论