How to use the length of a list

I’m using:

SWI-Prolog version online https://swish.swi-prolog.org/p/NBA.pl

I want the code to:

So this might be a noob question, but how can I get a length of a list?

So I am calling the predicate “jogosGanhos(Team)” and it should return a list of all games a team won, then I want to use the length of that list to get the number of wins and divide by the total of games to get a win percentage. How can I do this?

My code looks like this:

winPercentage(Equipa):-
	Wins is lenght(jogosGanhos(Equipa)),
    P is Wins / 82,
    format('\nA percentagem de vitórias da equipa '), write(Equipa),
    format(' é '), write( P).

You are using the correct predicate (length/2)

Instead of

Wins is lenght(jogosGanhos(Equipa))

use

length(jogosGanhos(Equipa),Wins)

also you spelled length wrong.

okay I thought that my ‘jogosGanhos’ predicate would return a list but it doesn’t, it gives me an error

Try these predicates

jogosGanhos(Equipa,Count) :-
    aggregate_all(count,(jogo(_,X,Equipa,CA,FA,CB,FB,CC,FC,CD,FD),(CA+CB+CC+CD)<(FA+FB+FC+FD)), Home_count),
    aggregate_all(count,(jogo(_,Equipa,X,CA,FA,CB,FB,CC,FC,CD,FD),(CA+CB+CC+CD)<(FA+FB+FC+FD)), Away_count),
    Count is Home_count + Away_count.

winPercentage(Equipa):-
    jogosGanhos(Equipa,Wins),
    P is Wins / 82,
    format('\nA percentagem de vitórias da equipa '), write(Equipa),
    format(' é '),write(P).

?- jogosGanhos(nets,Count).
Count = 37.

?- winPercentage(nets).

A percentagem de vitórias da equipa nets é 0.45121951219512196
true.

1 Like

A post was split to a new topic: Query runs one time then returns false

Some feedback on using Discourse which this site runs on.

  1. When adding Prolog source code, e.g.

test_clause(Arg1,Arg2) :-
do_1(Arg1),
do_2(Arg1,Arg2).

you should add ```prolog before the code and ``` after the code so that the Prolog code is highlighted correctly, e.g.

test_clause(Arg1,Arg2) :-
    do_1(Arg1),
    do_2(Arg1,Arg2).
  1. As the original poster (OP) to the topic you will get notifications. Others will not get automatic notifications unless you use @ with their tag, e.g. @c0rdeiro will cause you to get a notification. So if you want me to see a reply then please add @EricGT. :smiley:
1 Like

I think a key thing to understand is that the is thing is just for doing math. In general, predicates in Prolog don’t return values; instead, you use them to “unify” variables. It seems awkward (because, for instance, you can’t nest function calls), but can be very useful, because it lets you use the same predicate in a number of different ways!

e.g.

?- length([1,2,3], L).
 L = 3.
?- length(Lst, 3).
Lst = [_1, _2, _3].

So, your predicate jogosGanhos is going to unify the variable passed in with the list.
Therefore, you want to do something like

jogosGanhos(Teams),
length(Teams, Wins),
P is Wins / 82,
format("~w", [P]).
1 Like