selda
selda

Reputation: 179

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? ( I use prolog)

Upvotes: 1

Views: 2253

Answers (2)

user206428
user206428

Reputation:

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).

Upvotes: 4

thanos
thanos

Reputation: 5858

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).

Upvotes: 2

Related Questions