Webeks.net - freelance programming
freelance programming - php, Joomla, Zend ...
Home :: Articles :: Programming :: Prolog :: Prolog example - bookies exercise

Prolog example - bookies exercise

Written by Miha

Bookies wants to take some bets and of course they want to make profit with it. All they have are latest results from friendly matches. Predicate win(Team1, Team2, Result) means that the first team won the match with the Result.

Initial knowledge database

  1. win(portugal, saudi_arabia, 3-0).   
  2. win(mexico, paraguay, 2-1).f
  3. win(mexico, congo, 2-1).   
  4. win(argentina, portugal, 3-2).
  5. win(mexico, gana, 1-0).  
  6. win(portugal, croatia, 2-0).
  7. win(netherlands, ivory_coast, 3-1).   
  8. win(argentina, hungary, 2-1).
  9. win(netherlands, ecuador, 1-0).  
  10. win(portugal, egypt, 2-0).
  11. win(croatia, argentina, 3-2).   
  12. win(ivory_coast, slovenia, 3-0).
  13. win(south_corea, mexico, 1-0).   
  14. win(netherlands, mexico, 2-1).

Predicate to return difference between points

Write predicate gd(Team, GD) that returns the difference between all points that Team got and points that Team gave.

  1. gd(Team, GD):-
  2. %win
  3. findall(X,win(Team,_,X),D),
  4. sum(D,DWin),
  5. %loss
  6. findall(Y,win(Y,_,Team),D1),
  7. sum(D1,DLoss),
  8. GD is DWin - DLoss.
  9. sum([],0).
  10. sum([X|List],Sum):-
  11. sum(List,Sum1),
  12. Sum is X + Sum1.

What answers Prolog to following queries:

?- win(portugal, X, 2-0).

X = croatia ?;
X = egypt ?;
no

?- win(netherlands, X, _).

X =  ivory_coast ?;
X = ecuador ?;
X = ecuador ?;
no

?- win(X, mexico, _), !, win(mexico, Y, _).

X = south_corea,
Y = paraguay ? ;

X = south_corea,
Y = congo ? ;

X = south_corea,
Y = gana ? ;
no

?- win(X, Y, _-2).

X = argentina,
Y = portugal ? ;

X = croatia,
Y = argentina ? ;
no

 

How would you ask Prolog following questions (don't write predicates):

Which teams have been beaten by argentina?

?- win(argentina, X,_).

Did team1 won team2, team2 won team3 and team3 won team1?

?- win(X,Y,_),win(Y,Z,_),win(Z,X,_).

How many different teams did argentina played with?

?- findall(X,(win(X,argentina,_);win(argentina,X,_)),L),length(L,N).

List teams that won by at least two point difference.

findall(X,(win(X,_,N), N>=2),_List), setof(X,member(X,_List),List1).

Prolog predicate group() example

Teams will be arranged in groups. Predicate group(Team, Group) caries information in which group team is. Team is safe (it will surely go to next round) if it hasn't been beaten by a team from the same group. Following program was written by unskilled programmer and it has errors. Correct it.

safe(Team):-
group(Team, G), group(Opponent, G), \+win(Opponent, Team, _).

Proper program :)

safe(Team):-
(group(Team, Group),
group(Opponent,Group),
win(Opponent, Team,_)) -> fail;
true.

 


blog comments powered by Disqus