Converting a list into a term in Prolog

☆樱花仙子☆ 提交于 2020-02-20 09:21:27

问题


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:


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

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


来源:https://stackoverflow.com/questions/612604/converting-a-list-into-a-term-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!