English 中文(简体)
询问在数据库中找到最大的要素?
原标题:Prolog query to find largest element in database?
  • 时间:2010-10-29 14:31:29
  •  标签:
  • prolog

如果我界定了Prolog数据库中的所有数字,例如dig(0), dig(1), ......, dig(9)。 我能用什么问询来把人数最多的数字——在本案中是9人?

我尝试过这样的事情:

?- dig(N), dig(M), N > M.

但这只是首例可能,而不是最大数目。

问题回答

找到人数最多的候选人,请填写适当的询问,即:

  • 在校人数

  • 检查该位数是最大的(即没有其他位数)

因此,你可能想写像:

largest(N):-
    dig(N),
    not((
        dig(M),
        M > N
    )).

虽然最短的解决办法可能是:

?- dig(Max), +((dig(X), X > Max)).

概念上最简单的解决办法可能是:

?- findall(X, dig(X), Digits), max_list(Digits, Max).

But check out Max out of values defined by prolog clauses for more solutions, with better and worse complexities.

你可以通过查阅这一档案来检验这两个解决办法的速度:

:- between(1, 12345, X), assert(dig(X)), fail ; true.

:- time((findall(X, dig(X), Digits), max_list(Digits, Max))),
       write( Findall max:  ), write(Max), nl.

:- time((dig(Max), +((dig(X), X > Max)))), write( \+ max:  ), write(Max), nl.

On my 5 years old laptop it clearly shows that the findall-version is much faster if you have e.g. 12345 entries in your database.

% 37,085 inferences, 0.05 CPU in 0.06 seconds (87% CPU, 741700 Lips)
Findall max: 12345
% 76,230,375 inferences, 60.94 CPU in 72.30 seconds (84% CPU, 1250909 Lips)
+ max: 12345




相关问题
Prolog : Learning by example

I am trying to learn a little bit about swi-prolog (beyond the basic, useless programs). Can anyone explain (perhaps in pseudocode) what this sudoku solver and the related functions are doing? If ...

Working with lists in Prolog

First off let me state that this is part of a class exercise given as homework. But, the entire assignment is much more involved than the subject of this question. So.. I am searching through two ...

SWI-Prolog conditional statements

I m trying to write a function that will test to see if the word hello is contained in a list. If it is contained, i don t want it to say "true", i want it to say : "yes, the word hello is contained ...

prolog cut off in method

I have a question I would like to ask you something about a code snippet: insert_pq(State, [], [State]) :- !. insert_pq(State, [H|Tail], [State, H|Tail]) :- precedes(State, H). insert_pq(State, [...

Max out of values defined by prolog clauses

I know how to iterate over lists in Prolog to find the maximum, but what if each thing is a separate clause? For example if I had a bunch of felines and their ages, how would I find the oldest kitty? ...

热门标签