簡體   English   中英

從列表中刪除小於findall之后的值的元素

[英]Remove elements from list less than a value after findall

我有:

mymake(Answer_Max):-
    findall((Place, Cost), costOfLiving(Place, Cost), ResultList),
    delete_over(ResultList, Answer_Max).

costOfLiving在我的數據庫中,並且由每個位置和成本組成,例如:

costOfLiving(germany, 500).
costOfLiving(france, 500).

等等。 這樣ResultList就像[(germany, 500), (france, 500), ...]

我想刪除costOfLiving超過數字Answer_Max的數據庫的所有元素,但是我的delete_over無法正常工作。 就像這樣:

delete_over([], _).
delete_over([F|T], Max) :-
   F =.. [Place, Cost], % it fails here because the F is not a list, but two atoms I think
   ((id_state(Place), (Cost > Max)) -> deleteState(Place) ; true),
   % id_state and id_region checks that the place is defined in the database
   % deleteState and deleteRegion calls a specific retractall for the database
   ((id_region(Place), (Cost > Max)) -> deleteRegion(Place) ; true),
   delete_over(T).

我如何解決它以獲得我想要的東西? (以防其他錯誤)


使用我的解決方案 (和幫助)進行編輯

mymake(Answer_Max) :-   % I don't need the ResultList, but if needed just add as second parameter
    findall( (Place, Cost), ( costOfLiving(Place, Cost), Cost > Answer_Max ), ResultList ),
    maketolist(ResultList).

maketolist([]).
maketolist([(P,_)|T]) :- % all the elements are for deleting as their Cost is higher than the Max given
    (id_state(P) -> deleteState(P) ; true), % deleteState makes a retractall according to my needs on my database 
    (id_region(P) -> deleteRegion(P); true), % the same for deleteRegion with regions
    maketolist(T).

您可以僅在findall/3過濾結果。 順便說一句, mymake應該有第二個論點來回答。

costOfLiving(germany, 500). 
costOfLiving(france, 500).

mymake(Answer_Max, ResultList) :-
    findall( (Place, Cost)
           , ( costOfLiving(Place, Cost)
             , Cost >= Answer_Max
             )
           , ResultList
           ).

最后:

?- mymake(100,X).
X = [ (germany, 500), (france, 500)].

?- mymake(600,X).
X = [].

您可以直接從數據庫中撤回,而無需構建列表,但是如果需要此結構,則此處是必需的更正:

delete_over([F|T], Max) :-
   F = (Place, Cost), ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM