Construct a predicate called fPairsAtoms/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.
Example:
fPairsAtoms(sA,[[basA,absAb],[ab,bbsA],[sA,abbsB],[bsA,sAsB],[sA,bb]],X)
Result:
X = [[sA,abbsB],[sA,bb]]
I do not understand ..... What should I face these types of exercises? Can you help me find a solution?
Today I started with prolog, I am a newbie in every way.
To filter the pairs in the list, you need to traverse it while comparing the given atom with the first element of each pair. A trivial predicate to traverse a list would be:
The predicate in your problem description is terribly named and don't follow recommended Prolog coding guidelines. Let's rename it to
filter_pairs_by_key/3
and change the argument order tofilter_pairs_by_key(Pairs, SearchKey, FilteredPairs)
. Also, the recommended representation for a pair in Prolog isKey-Value
. There are standard predicates and library predicates that expect this representation (e.g.keysort/2
). Based on thetraverse/2
predicate template and the code style recommendations, we can write:Note that I'm using two clauses for the non-empty list case: one when the pair key matches the atom and one when the match fails.
Sample call:
More can be said about this problem and this particular solution but, as mentioned in the comments, this is not a beginners exercise. Consider the comments recommendations and after being comfortable with Prolog list notation play with this solution.
If you've just started today, it probably is a bit too soon for you to tackle this problem.
First you should understand what Prolog terms are:
atoms
, logicalVariables
, compound termsfoo(x,X,bar(baz))
.Then you should understand unification,
a = a
,a = A
,A = a
,A = foo(a)
,foo(A) = foo(a)
,[atom, B] = [A, bar]
.You should understand lists representation, where
so that unifying
[A | B] = [a]
succeeds, resulting in also unifyingA = a
andB = []
, but unifying[A | B] = []
fails.Then you need to understand predicates, which under procedural interpretation mean,
So that
is a perfectly valid, though exceedingly narrow, definition of one.
But then so are also
and so also
and thus
But on the other hand, in cases were there was no match, we saw that it is
So which one of the two clauses, that we've ended up with,
is the right one? The answer is: both!