[英]How to keep track of how many items in a list are greater than the head element in prolog
我希望跟蹤給定列表中有多少項目大於 head 元素。 我嘗試使用增量關系,並嘗試使用更大的元素構建一個新列表,但我沒有成功。 這就是我一直在使用的:
pullHead([H|T]) :-
isGreater(H,T).
isGreater(X,[H|T]) :-
X > H -> inc(Count,Temp),
isGreater(X,T);
isGreater(X,T).
inc(X,Y) :-
X is Y+1.
或者
pullHead([H|T]) :-
isGreater(H,T).
isGreater(X,[H|T]) :-
X > H -> append(X,List,List),
isGreater(X,T);
isGreater(X,T).
length(List,Count).
我的目標是讓元素數量大於存儲在 Count 中的頭部。
Example: List = [4,7,0,8,1,2,3]
Count = 2
我已經瀏覽了 prolog 開發頁面,試圖了解如何使這樣的事情工作,但無濟於事。 我不太確定我是否打算以正確的方式創建一個新列表。 看起來這些關系應該有效,但是正確分配變量或遞歸調用一定存在問題嗎?
這個怎么樣:
% The "entry predicate"
occurrences_greater_than_head([LV|Xs],N) :-
ogth_2(Xs,LV,0,N).
% The "entry predicate" calls a helper predicate
% having three "input parameters"
%
% +List, +LimitValue, +Counter
%
% and a "I/O parameter" that can be passed in (then the predicate
% verifies its value) or left unbound, in which case it will be
% bound to a numeric value that is the sought result:
%
% ?Limit.
%
% That is to say, the intended use of the predicate is:
%
% ogth_2(+List,+LimitValue,+Counter,?Result).
%
% It recurses through List, increasing Counter as it goes (an
% "accumulator values") and unifies the Counter with Result when the
% end of the list has been reached, thus communicating the final
% count to the original caller.
ogth_2([],_,C,C). % end case: unify Counter and Result
ogth_2([X|Xs],LV,C,R) :- % Case of:
X =< LV, % "smaller"
ogth_2(Xs,LV,C,R). % There is nothing to do here; call yourself
% with a smaller list and the same C
ogth_2([X|Xs],LV,C,R) :- % Case of:
X > LV, % "larger"
CN is C+1, % Actual arithmetic evaluation
ogth_2(Xs,LV,CN,R). % Call yourself with smaller list and CN,
% thus the C in the next activation will be CN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.