Calculating variance in prolog
i have made a function in Prolog:-
mean(L, M) :-
sum(L, S),
length(L, N),
M is S/N.
sum([],0).
sum([H|T],Y):-
sum(T,X),
Y is X + H.
variance([],0).
variance([H|T], M, VO):-
variance(T,M,Y),
VO is( Y + ((H-M)*(H-M))).
statsList(L, M, V1) :-
sum(L, S),
length(L, N),
M is S/N,
variance(L, M, VO),
开发者_如何学编程 V1 is V0/N.
for some reason when I try to calculate the variance it always replies "false" as so: variance([1,2,3],2,VO) or statsList([1,2,3],M,VO)
However if I use this just to test it works:
variance([],0).
variance([H|T], VO):-
variance(T,Y),
VO is( Y + ((H-2)*(H-2))).
Can someone tell me where I am going wrong?
variance([],0).
variance([H|T], M, VO):-
variance(T,M,Y),
VO is( Y + ((H-M)*(H-M))).
The first clause defines a predicate variance/2
(two arguments) while the second defines variance/3
. The latter predicate then calls itself recursively until it hits the empty list, which it cannot handle.
You should define a proper base case for variance/3
. In Prolog, clauses with the same predicate name but different arity (number of arguments) define different predicates.
The error does not show up in your test code since there you define variance/2
with a base case and a recursive case.
In your first code you have defined two predicates variance/2 and variance/3 (one with 2 arguments and the other with 3 arguments). You have probably misspelled the first predicate. It should read
variance([], _, 0).
精彩评论