计算Prolog中给定列表的正数列表

Calculating List of positive numbers of a given list in Prolog

我试过通过以下方式自行解决:

list_of_positives(L1, L2) :- 
   list_of_positives(L1, L2, []).
list_of_positives([], L, L).
list_of_positives([H|T], L2, L3) :- 
   (   H > 0 
   ->  list_of_positives(T,L2,[H|L3])
   ;   list_of_positives(T,L2,L3) 
   ).

此解决方案的问题是我得到的响应是一个反转的正数列表。有人可以帮我找到一种方法来以“正确顺序”获取列表吗?

您可以通过以下方式解决问题:

positives([], []).

positives([H|T], P) :-
   (   H > 0
   ->  P = [H|R]     % desired order!
   ;   P = R),
   positives(T, R) .

示例:

?- positives([2,-3,6,-7,1,4,-9], P).
P = [2, 6, 1, 4].

您想使用差异列表、非封闭列表或开放列表。所以,像这样:

positives( []     , []     ) .  % An empty list has not positives, and closes the list.
positives( [N|Ns] , [N|Rs] ) :- % For a non-empty list, we prepend N to the result list
  N > 0,                        % - if N is positive
  positives(Ns,Rs)              % - and recurse down.
  .                             %
positives( [N|Ns] , Rs     ) :- % For non-empty lists, we discard N
  N =< 0,                       % - if N is non-positive
  positives(Ns,Rs)              % - and recurse down.
  .                             %