如何解决计算 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.
. %
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。