Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Calculate the average of an Existing list inside Knowledge base of prolog code?

Tags:

prolog

I have been trying for instance to have a list [1,3] and calculate its average inside the code without inputing the least itself. I'm not sure of the correct syntax to make it work, only the first line has a problem since it works perfectly fine if I called average and input the numbers when I run prolog.

average([1,3],X).


average(List, Result) :- sum1(List, Len), sum(List, Sum), Result is Sum / Len.

sum([], 0).

sum([H|T], Sum) :- sum(T, Temp), Sum is Temp + H.


sum1([],0).

sum1([_|B],L):-sum1(B,Ln), L is Ln+1.
like image 516
Amrhussein Avatar asked Nov 28 '25 22:11

Amrhussein


2 Answers

Well, you don't want to input list all the time. It means, that you should have predicate something like my_list/1 and use it in your program.

my_list( [1,3] ).

average_easy( List, Avg ) :-
    sum_( List, Sum ),
    length_( List, Length ),
    Avg is Sum / Length.

sum_( [], 0 ).
sum_( [H|T], Sum ) :-
    sum_( T, Temp ),
    Sum is Temp + H.

length_( [], 0 ).
length_( [_|B], L ):-
    length_( B, Ln ),
    L is Ln+1.

main :-
    my_list( X ),
    average_easy( X, Ans ),
    writeln((X, Ans)).

So, what we've got now, is

?- [your_program_name].
% your_program_name compiled 0.00 sec, 64 bytes
true.

?- main.
[1,3],2
true.

Btw, there are length/2 predicate, already built-in in swi-prolog.

like image 107
ДМИТРИЙ МАЛИКОВ Avatar answered Dec 02 '25 04:12

ДМИТРИЙ МАЛИКОВ


avglist(L1,Avg):-sum(L1,0,S),length(L1,0,L),Avg is S/L.

sum([H|T],A,S):-A1 is A+H,sum(T,A1,S).
sum([],A,A).

length([H|T],A,L):-A1 is A+1,length(T,A1,L).
length([],A,A).

this is a simple method to calculate the average of a list in swi prolog

like image 38
niharika kumar Avatar answered Dec 02 '25 04:12

niharika kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!