prolog - 如何从术语中获取简单元素?
问题描述
我想从术语中获取简单的元素并将它们返回到列表中。
我的代码:
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]
解决方案
正如我在评论中提到的,解决方案需要是递归的,并且需要更多的参与。
这是一个可能的解决方案,其中我留下了空白点供您整理:
% 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
再次调用某些内容。
推荐阅读
- python - 无法分配“'nimaaram'”:“Food.user”必须是 Django 中的“用户”实例
- javascript - JavaScript 将两个多维数组合并为唯一数组
- python - PyQt5 Designer对话框自动关闭..此代码无法访问
- python - 复制文件的原始创建日期
- python - Plotly:如何使用下拉菜单按年、月和日对数据进行子集化?
- c - 如何解决列表和文件的“C”中的“分段错误”错误
- javascript - Discord.js V12 粗鲁的话过滤器不起作用
- c# - 如何处理异常并使用 Rx 重复
- ruby-on-rails - Rails:如何记录 rake 任务中抛出的所有异常
- laravel - Laravel-令牌不是在注册请求时创建的