问题
I use swi prolog. I have a fact base like this consisting of facts with arity 4.
attribute(a1,a2,a3,a4).
data(yes,no,no,no).
data(yes,no,yes,no).
data(yes,yes,yes,no).
data(yes,yes,yes,yes).
data(no,yes,yes,yes).
And my code calculate probability of Result when I call pbayes(yes,no,no,no,Result);
p(ColumnName,ColumnValue,Result):-
(
(ColumnName==a1->findall(ColumnValue,data(ColumnValue,_,_,_),Liste));
(ColumnName==a2->findall(ColumnValue,data(_,ColumnValue,_,_),Liste));
(ColumnName==a3->findall(ColumnValue,data(_,_,ColumnValue,_),Liste));
(ColumnName==b->findall(ColumnValue,data(_,_,_,ColumnValue),Liste))
),
length(Liste,Sayac),
findall(_,data(_,_,_,_),TumListe),
length(TumListe,TumSayac),
Result is Sayac/TumSayac.
pcond(ColumnName,ColumnValue,BValue,Result):-
(
s(ColumnName==a1->findall(ColumnValue,data(ColumnValue,_,_,BValue),Liste));
(ColumnName==a2->findall(ColumnValue,data(_,ColumnValue,_,BValue),Liste));
(ColumnName==a3->findall(ColumnValue,data(_,_,ColumnValue,BValue),Liste))
),
length(Liste,Sayac),
findall(BValue,data(_,_,_,BValue),BListe),
length(BListe,BSayac),
Result is Sayac/BSayac.
pbayes(B,A1,A2,A3,Result):-
pcond(a1,A1,B,ResultCondA1),
pcond(a2,A2,B,ResultCondA2),
pcond(a3,A3,B,ResultCondA3),
p(b,B,ResultB),
(Mult1=0->Result is 0,!;true),
p(a1,A1,ResultA1),p(a2,A2,ResultA2),p(a3,A3,ResultA3),
Mult2 is ResultA1 * Result2 * ResultA3,
(Mult=0->Result is 0; Result is Mult1/Mult2).
I try to generalize my code to solve problems with different arities.
Such as arity count can be 6 in fact base like this:
attribute(a1,a2,a3,a4,a5,a6).
data(yes,yes,yes,no,no,no).
data(yes,yes,yes,no,no,yes).
My program has to adjust itself to arity. Do you have any idea how I can achieve this?
回答1:
putting all the arguments in a list like
attribute([a1,a2,a3,a4,a5,a6]).
data([yes,yes,yes,no,no,no]).
data([yes,yes,yes,no,no,yes]).
and then recursively process the data is what I would do.
if, for some reason, you want to have predicates with different arities, you could use the =../2 operator to get the arguments in a list and then process them
or you can write code for each arity XD
来源:https://stackoverflow.com/questions/5949012/how-to-generalize-program-according-to-arity-in-prolog