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

问题描述

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

list_of_positives(L1,L2) :- 
   list_of_positives(L1,L2,[]).
list_of_positives([],L,L).
list_of_positives([H|T],L3) :- 
   (   H > 0 
   ->  list_of_positives(T,[H|L3])
   ;   list_of_positives(T,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,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.
  .                             %