序言列表和过滤 [英] Prolog list and filtering
问题描述
我在Prolog练习中遇到问题.我正在尝试在家中独自学习计算机科学,并且正在做一系列从互联网上进行的练习.
I have a problem with a Prolog exercise. I'm trying to study Computer Science alone at my home, and I'm doing a series of exercises I've taken from the Internet.
问题如下;
构造一个称为
filteringPairsAtoms/3
的谓词,以便给定一个原子(第一个参数)和一个对对,通过仅选择具有以下对的对,将第三个参数与过滤后的对对统一第一个成分是第一个参数的原子.
Construct a predicate called
filteringPairsAtoms/3
so that given an atom (first argument), and a list of pairs, unify a third parameter with the filtered list of pairs by selecting only the pairs that have the first component as the atom of the first argument.
示例
filteringPairsAtoms(sA,[[basA,absAb],[ab,bbsA],[sA,abbsB],[bsA,sAsB],[sA,bb]],X)
必须导致
X = [[sA,abbsB],[sA,bb]]
我正在尝试解决问题,但是我没有人要问,因为我一个人学习,也没有教授写东西.
I'm trying to solve it but I don't have anyone to ask, because I'm learning alone, and don't have a professor to write to or something.
欢迎任何帮助.
谢谢!
推荐答案
您可以从已有的内容开始:
You can start from what you already have:
filteringPairsAtoms(sA, [[basA,absAb],[ab,bbsA],[sA,abbsB],[bsA,sAsB],[sA,bb]], X) :-
X = [[sA,abbsB],[sA,bb]].
这是一个很好的开始.但是我们知道更多:肯定是这种情况
That's as good a start as any. But we know more: it must be the case that
filteringPairsAtoms(sA, [[sA,abbsB],[bsA,sAsB],[sA,bb]], X) :-
X = [[sA,abbsB],[sA,bb]].
%% and
filteringPairsAtoms(sA, [[bsA,sAsB],[sA,bb]], X) :-
X = [[sA,bb]].
%% and
filteringPairsAtoms(sA, [[sA,bb]], X) :-
X = [[sA,bb]].
%% and
filteringPairsAtoms(sA, [], X) :-
X = [].
比较顺序子句,我们还注意到它必须是
Comparing the sequential clauses, we also notice that it must be
filteringPairsAtoms(sA, [[sA,abbsB] | [[bsA,sAsB],[sA,bb]] ], X) :-
sA = sA,
X = [[sA,abbsB] | Y],
filteringPairsAtoms(sA, [[bsA,sAsB],[sA,bb]], Y).
(这只是上面的前两个子句的总和);和
(this is just the first two clauses from above, combined); and
filteringPairsAtoms(sA, [[bsA,sAsB] | [[sA,bb]] ], X) :-
dif( sA, bsA),
X = Y,
filteringPairsAtoms(sA, [[sA,bb]], Y).
剩下要做的就是通过用逻辑变量替换具体术语来概括.像这样:
All that's left for you to do, is generalize this by replacing concrete terms with logical variables. Like this:
filteringPairsAtoms(SA, [Head | Tail ], X) :-
Head = [BsA, _]
dif( SA, BsA),
X = Y,
filteringPairsAtoms(SA, Tail, Y).
,并将其完全执行到最后.
and carry this out fully to the end.
这篇关于序言列表和过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!