Prolog 清除负元素列表而不使用切割 [英] Prolog Clear List of negative elements without using cuts

查看:37
本文介绍了Prolog 清除负元素列表而不使用切割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Prolog 中编写一个过程来清除其负元素的整数列表并在新列表中返回结果?不使用切割但可以使用否定.

How do I write a procedure in Prolog that clears a list of integers of its negative elements and returns the result in a new list? Without using cuts but can use negation.

例如:

?- filter([1,0,-6,7,-1],L).
L = [1,0,7];
no

推荐答案

你说得差不多了.您的解决方案是:

You have it almost right. Your solution was:

filter([],[]).
filter([H|T],S) :-
  H<0,
  filter(T,S).
filter([H|T],S) :-
  H>=0,
  filter(T,[H|S]).

基本情况和项目为负的情况是正确的.问题在于最后一种情况.一旦您检查该项目是非负的,您就知道该项目将出现在结果列表中.因此,您应该进行递归并返回一个列表,其中包含您检查过的元素 (H) 和递归返回的列表.因此,最后一个子句应该是

The base case and the case where the item is negative are right. The problem is with the last case. Once you checked that the item is nonnegative you know that the item will be on the resulting list. Therefore you should do the recursion and return a list that contains the element you have checked (H) and the list returned by recursion. Thus, the last clause should be

filter([H|T],[H|S]) :-
  H>=0,
  filter(T,S).

这篇关于Prolog 清除负元素列表而不使用切割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆