将整数列表拆分为正整数列表和负整数列表

将整数列表拆分为正整数列表和负整数列表

本文介绍了将整数列表拆分为正整数列表和负整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在Prolog中创建谓词,以将整数列表分为正整数列表和负整数列表.

I've been trying to create a predicate in Prolog which splits a list of integers into a list of positive integers and into a list of negative integers.

示例查询具有预期结果:

Sample query with expected result:

?- split([1,-2,3,4,-8],X,Y).
X = [1,3,4],
Y = [-2,-8].

这是我到目前为止得到的代码:

This is the code I got so far:

split([], [], []).
split([Head|Tail], List1, List2) :- split(Tail, [Head|List1], List2), Head>=0.
split([Head|Tail], List1, List2) :- split(Tail, List1, [Head|List2]), Head<0.

我似乎无法弄清楚我在做错什么.

I can't seem to figure out what I'm doing wrong.

推荐答案

递归部分不太正确.

split([], [], []).
split([Head|Tail], [Head|List1], List2) :- Head>=0, split(Tail, List1, List2).
split([Head|Tail], List1, [Head|List2]) :- Head<0, split(Tail, List1, List2).

如果Head >= 0,应将Head添加到肯定列表中,而当Head < 0时,应添加到否定列表中.

The Head should be added to the positive list if Head >= 0 and to the negative list when Head < 0.

此外,最好在开头检查Head 的符号,因为这样可以防止不必要的递归调用.

Moreover, checking the sign of Head at the beginning is better, because it will prevent unnecessary recursive calls.

这篇关于将整数列表拆分为正整数列表和负整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:11