展平术语 Prolog [英] Flatten term Prolog
问题描述
我是 Prolog 的新手,我正试图解决这样的问题,所以我希望有人能提供帮助.
我想实现一个三元谓词 flatten_term(Term, Function_symbol, Flattened_term)
如果 Flattened_term
是从 Term
获得的Function_symbol
的嵌套出现.假设 Term
不包含Prolog 变量和不检查列表的列表.
I'm new in Prolog and I was trying to solve sucha problem so i wish if anybody could help.
I want to implement a ternary predicate flatten_term(Term, Function_symbol, Flattened_term)
that succeeds if Flattened_term
is obtained from Term
by flattening out all
nested occurrences of Function_symbol
. It is assumed that Term
contains no
Prolog variables and no lists without checking the list.
?- flatten_term(f(f(x)), f, Flattened_term).
Flattened_term = f(x).
?- flatten_term(f(x), f, Flattened_term).
Flattened_term = f(x).
?- flatten_term(a, f, Flattened_term).
Flattened_term = a.
?- flatten_term(g(f(x)), f, Flattened_term).
Flattened_term = g(f(x)).
?- flatten_term(g(f(f(x))), f, Flattened_term).
Flattened_term = g(f(x)).
推荐答案
我使用下面的代码来计算一个术语中的项目.也许这与您要寻找的相似?
I'm using the code below in order to count the items in a term. Maybe this is similar to what you are looking for?
?- flatten_term(5+3*x=10,List).
List = [=, +, 5, *, 3, x, 10].
这是源代码:
flatten_term(Term,[Term]):-
atomic(Term),!.
flatten_term(Term,Flat):-
Term =.. TermList,
flatten_term_list(TermList,Flat),!.
flatten_term_list([],[]):-!.
flatten_term_list([H|T],List):-
flatten_term(H,HList),
flatten_term_list(T,TList),
append(HList,TList,List),!.
这篇关于展平术语 Prolog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!