开发者

compute in prolog

开发者 https://www.devze.com 2023-01-27 09:03 出处:网络
I know in prolog we ask for is that true or false , can we also do compu开发者_Python百科te for example average and how the predicate look like?Of course you can compute the average of a list of numbe

I know in prolog we ask for is that true or false , can we also do compu开发者_Python百科te for example average and how the predicate look like?


Of course you can compute the average of a list of numbers and the predicate would look like this:

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

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

Then you get:

?- average([1, 2, 3], X).
X = 2.


Prolog does not ask if something is true of false. That is a common misconception. Prolog tries to unify query goals with program predicates. If it succeeds, it returns an assignment to the variables appearing in the query. If it fails - Which is not supposed to be the common case - It returns "false".

As for averages, see 3electrologos' answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消