mike91827
mike91827

Reputation: 43

Prolog finding max of list with two values

So I am using prolog and i Have a funcntion like this:

ratingList(X):-goalKeeperRating(X,A),centreForwardRating(X,B),secondStrikerRating(X,C),centreDefenseRating(X,D),fullBackRating(X,E),centerMidfieldRating(X,F),attackingMidfieldRating(X,G),defendingMidfieldRating(X,H),
Y=[[goalKeeper,A],[centerForward,B],[secondStriker,C],[centerDefense,D],[fullBack,E],[centerMidfield,F],[attackingMidfieldRating,G],[defendingMidfieldRating,H]],
maxlist(Y,N),N=[L,M],write('Best Position ' + L + ' with rating ' +M).

Basically the first line finds numbers and put it in the second element, then we put numbers in a list (Y). Everything in Y is a list of length 2 with a soccer position name plus the number we got. MaxList just finds the maxinum number. it looks like this

maxlist([A],A).
maxlist([A,B|C],D):- A=[_,X],E=[_,Y],D=[_,Z],maxlist([B|C],E),max(X,Y,Z),.
max(A,B,A):-A>=B.
max(A,B,B):-A<B.

However, whenever I try to print the word it always results in printing the address. Is there anyway I can fix this?

Upvotes: 0

Views: 248

Answers (1)

rajashekar
rajashekar

Reputation: 3793

You are constructing D without giving it's first element any value. The max function must work with the whole element not just the second element of the list. In your own style

maxlist([A], A).
maxlist([A, B | As], M) :-
    maxlist([B | As], M1), max(A, M1, M).
max(A, B, A) :- A = [_, X], B = [_, Y], X >= Y.
max(A, B, B) :- A = [_, X], B = [_, Y], X < Y.

A iterative way to find the maximum of the list

maxlist([X | Xs], Max) :- maxlist(Xs, X, Max).
maxlist([], A, A).
maxlist([B | Bs], A, C) :-
    A = [_, X], B = [_, Y],
    (X > Y -> T = A ; T = B),
    maxlist(Bs, T, C).

Upvotes: 2

Related Questions