Daesos
Daesos

Reputation: 109

How to transform a term into a list in Prolog

How can i transform a term like: 3 * y * w * t^3 in a list made of: List = [3, *, y,...], without using the following predicate:

t2l(Term, List) :-
    t2l_(Term, List-X),
    X = [].
t2l_(Term, [F|X]-X) :-
    Term =.. [F],
    !.
t2l_(Term, L1-L4) :-
    Term =.. [F, A1, A2],
    t2l_(A1, L1-L2),
    L2 = [F|L3],
    t2l_(A2, L3-L4).

Is there a simple way?

Upvotes: 1

Views: 528

Answers (2)

Daesos
Daesos

Reputation: 109

Thanks mat for answering, i forgot to close the question. However i have created a new predicate that solve the problem:

term_string(Term, X),
string_codes(X, AList),
ascii_to_list(AList, Y).

ascii_to_list([X | Xs], [Y | Out]) :-
    X >= 48,
    X =< 57,
    !,
    number_codes(Y, [X]),
    ascii_to_list(Xs, Out).
ascii_to_list([X | Xs], [Y | Out]) :-
    char_code(Y, X),
    ascii_to_list(Xs, Out).
ascii_to_list([], []).

Upvotes: 0

mat
mat

Reputation: 40768

In Prolog, everything that can be expressed by pattern matching should be expressed by pattern matching.

In your case, this is difficult, because you cannot collectively distinguish the integers from other arising terms by pattern matching with the defaulty representation you are using.

In the following, I am not solving the task completely for you, but I am showing how you can solve it once you have a clean representation.

As always when describing a list in Prolog, consider using notation:

term_to_list(y) --> [y].
term_to_list(w) --> [w].
term_to_list(t) --> [t].
term_to_list(i(I)) --> [I].
term_to_list(A * B) -->
        term_to_list(A),
        [*],
        term_to_list(B).
term_to_list(A^B) -->
        term_to_list(A),
        [^],
        term_to_list(B).

In this example, I am using i(I) to symbolically represent the integer I.

Sample query and result:

?- phrase(term_to_list(i(3)*y*w*t^i(3)), Ls).
Ls = [3, *, y, *, w, *, t, ^, 3].

I leave converting the defaulty representation to a clean one as an easy exercise.

Upvotes: 1

Related Questions