Search code examples
prolog

finding players in the same the team in prolog


I'm trying to solve a prolog question. I'm trying to print the players who is playing in Arsenal. I couldn't solve the problem.


player(rick,arsenal)
player(tom,dortmund)
player(paul,bayern)
player(tim,liverpool)
player(john,arsenal)
player(andrew,arsenal)

the output has to be:


?- sameteam(????)

X= [rick,john,andrew]

Solution

  • First, your facts need to be terminated with a "." to be correct Prolog syntax

    player(rick,arsenal).
    player(tom,dortmund).
    player(paul,bayern).
    player(tim,liverpool).
    player(john,arsenal).
    player(andrew,arsenal).
    

    In "relational database fashion", let's first collect the ground atoms (in the sense of "logic atoms", i.e. "facts") that match the condition "plays at arsenal".

    Fire up your preferred Prolog, and then:

    ?- [user].
    |: player(rick,arsenal).
    |: player(tom,dortmund).
    |: player(paul,bayern).
    |: player(tim,liverpool).
    |: player(john,arsenal).
    |: player(andrew,arsenal).
    |: ^D% user://2 compiled 0.00 sec, 6 clauses
    true.
    
    ?- player(Who,arsenal).
    Who = rick ;
    Who = john ;
    Who = andrew.
    

    Now we just need to "collect them into a list" and we can do that easily using setof/3:

    ?- setof(Who,player(Who,arsenal),Players).
    Players = [andrew, john, rick].
    

    This is all bog-standard "asking the database" work.

    We can pack the above into a predicate for easier usage:

    ?- [user].
    |: sameteam(Players) :- setof(Who,player(Who,arsenal),Players).
    |: ^D% user://3 compiled 0.00 sec, 1 clauses
    true.
    
    ?- sameteam(Players).
    Players = [andrew, john, rick].