首页 > 解决方案 > 如何从术语中获取简单元素?

问题描述

我想从术语中获取简单的元素并将它们返回到列表中。

我的代码:

getSimple(T, R) :- 
  compound(T), 
  T =.. [_|R]

此查询有效

getSimple(f(1, 2, a), X)

例子:

X = [1, 2, a]

此查询返回错误结果:

getSimple(f(2, 3, g(a)), X)

例子:

X = [2, 3, g(a)]

预期的:

X = [2, 3, a]

标签: prolog

解决方案


正如我在评论中提到的,解决方案需要是递归的,并且需要更多的参与。

这是一个可能的解决方案,其中我留下了空白点供您整理:

% We'll use an auxiliary predicate that handles a list of terms
term_args(Term, Args) :-
    term_list_args([Term], Args).

% This predicate recursively handles a list of terms, each of which is or is not be compound
%    ...so you have to check!
term_list_args([Term|Terms], Args) :-
    (   compound(Term)
    ->  Term =.. [_|TermArgs],                     % If this term is a compound term
        ___,     % Recursively process the term's arguments (TermArgs)
        ___,     % Recursively process the remaining terms (Terms)
        ___      % append the results of the two queries above to obtain Args
    ;                                              % Otherwise, if Term is not compound
        ___,     % Recursively process the remaining terms (Terms) - obtaining TermArgs
        Args = [Term|TermArgs]
    ).
term_list_args([], []).  % base case: An empty list of terms corresponds to an empty arg list

试着填上上面的空白。请注意,“递归”意味着您将term_list_args/2再次调用某些内容。


推荐阅读