4
votes

What is the best way of converting a Prolog list into a Prolog term (that is not a list), in terms of efficiency, and using existing built-in predicates as much as possible?

The interface and usage examples would be the following.

%% list_to_term(+List:list, +Functor:atom, -Term:term)
%
% Usage:
%
% ?- list_to_term([], myfunctor, Term).
% Term = myfunctor.
%
% ?- list_to_term([a, b, [c], D, 2], myfunctor, Term).
% Term = myfunctor(a, b, [c], D, 2).

I.e. the given list (which is actually a nested term) is flattened into a term with the given name.

I'm not saying that it makes sense to do this. (But if you think that it does, please provide a usecase in your answer.)

1
What should be the answer for list_to_term([X,Xs], '.', Term)? You demand that it should not be a list ... :-) - false
Thanks for pointing this out. ;) Now that I read this question after 3 years it doesn't really make sense to me as it is. I would delete it altogether if I could. - Kaarel
It is a question from a beginner's perspective. Here is the place for it. - false

1 Answers

8
votes

You need to use the =.. operator, like so:

list_to_term(List, Functor, Term) :-
    Term =.. [Functor | List].