0

Let's say we have this database:

choice(marie, [peru,greece,vietnam]).
choice(jean,  [greece,peru,vietnam]). 
choice(sasha, [vietnam,peru,greece]). 

We want to know the best country based on the list of choice of each person, element 0 in the list is category 3, second category 2, and third category 1, So by asking:

?- where([marie,jean,sasha],Country).

we should get: Country = peru

This is what I have so far but I can't get the value associated with a country to go back up the chain of choice.

where([],Count).
where([Name|L], Count) :-
    where(L, Count), 
    choice(Name,LPref), 
    calc(LPref,0,0,0,4) .
calc([],P,G,V,1).
calc([H|L],P,G,V,N) :-
    N1 is N-1,
    calc(L, P,G,V,N1),
    pays(H,P,G,V,N1).

pays(H,P,G,V,N) :- 
    H == 'peru',
    P is P+N.
pays(H,P,G,V,N) :- 
    H == 'greece',
    G is G+N.
pays(H,P,G,V,N) :- 
    H == 'vietnam',
    incr(V,N).

incr(I, I).
incr(I, K) :-
    J is I + 1,
    pays(H,J,G,V,N),
    incr(J, K).
Guy Coder
  • 24,501
  • 8
  • 71
  • 136
Mat
  • 31
  • 3
  • This suffers from the confusion of seeing "predicates" as "functions that return a value". They are not, they just return "true" or "false" and the "values to return" are set by setting constraints among the predicate arguments. For example `pays(H,P,G,V,N):- H == 'peru',P is P+N.` does nothing at all, it computes `P+N` then verifies that it is equal to `P`, which is generally going to cause it to return `false` (`pays` is `country, right?). – David Tonhofer Mar 18 '20 at 07:12
  • 1
    See: [List processing calculation in prolog to find a destination friends will visit](https://stackoverflow.com/q/60709144/1243762). It is the exact same homework problem. While not a duplicate you should have looked at other questions. – Guy Coder Mar 18 '20 at 09:28
  • `I can't get the value associated with a country to go back up the chain of choice.` - You need an `accumulator`. Just Google for `Prolog accumulator` and you will find many examples – Guy Coder Mar 18 '20 at 09:36
  • Without running your code, off the top of my head, your base case `calc([],P,G,V,1).` has the values, but needs to return the values back, e.g. `calc([],P,G,V,1,P,G,V).` Yes the variables are in there twice, they are unified with the result variables to be passed back, e.g. `pays(H,P,G,V,N,PR,GR,VR).` – Guy Coder Mar 18 '20 at 14:43

0 Answers0