[英]Prolog Lists, Add 1 to tail of the list
I'm trying to add either 1 or 2 to numbers in a list in SWI-Prolog. 我正在尝试在SWI-Prolog中的列表中的数字上添加1或2。
I've managed to add 1 or 2 to the head of the list however I'm having difficulties adding onto each element on the tail of the list. 我设法在列表的开头添加了1或2,但是在添加到列表末尾的每个元素时遇到了困难。 I don't want to add 1 or 2 to EVERY element at the same time just at separate times.
我不想在单独的时间同时向每个元素添加1或2。 Ie If my input is add([2,3,4], X).
即如果我的输入是add([2,3,4],X)。
I would like the possibilities of X to be the following: X = [3,3,4]
X = [4,3,4]
X = [2,4,4]
X = [2,5,4]
X = [2,3,5]
X = [2,3,6]
我希望X的可能性如下:
X = [3,3,4]
X = [4,3,4]
X = [2,4,4]
X = [2,5,4]
X = [2,3,5]
X = [2,3,6]
My code at present is: 我目前的代码是:
add([],[]).
add([H1|T1],[H2|T2]) :-
is(H2,+(H1,1)), T1=T2;
is(H2,+(H1,2)), T1=T2.
Obviously this only adds 1 or 2 onto the head of the list and not the tail. 显然,这只会在列表的开头加上1或2,而不是结尾。 Therefore does anyone know how I may go about adding 1 or 2 onto the elements in the tail of my list?
因此,有人知道我如何将1或2添加到列表尾部的元素上吗?
First define a predicate addX/3
that will add X to one of the members of the first list: 首先定义一个谓词
addX/3
,它将X加到第一个列表的成员中:
addX([], [],_). % base case
addX([H|T], [H1 | T], X) :- H1 is H + X. % add to first element
addX([H|T], [H | T1], X) :- addX(T, T1, X). % or retain the first element and add to some element in the tail
Than using it define your add
predicate as addX
with X=1
or X=2
: 与使用它相比,将您的
add
谓词定义为X=1
或X=2
addX
:
add(L, R) :- addX(L, R, 1).
add(L, R) :- addX(L, R, 2).
Testing: 测试:
?- add([2,3,4], X).
X = [3, 3, 4] ;
X = [2, 4, 4] ;
X = [2, 3, 5] ;
X = [2, 3, 4] ;
X = [4, 3, 4] ;
X = [2, 5, 4] ;
X = [2, 3, 6] ;
X = [2, 3, 4].
sometime more verbose can be clearer: 有时更详细可以更清楚:
add([],[]).
add([H1|T],[H2|T]) :-
H2 is H1+1.
add([H1|T],[H2|T]) :-
H2 is H1+2.
add([H|T1],[H|T2]) :-
add(T1,T2).
now alternatives are listed out, the last one just handles - recursively - the remaining elements 现在列出了替代方案,最后一个只是递归地处理其余元素
Anyway, your code is just missing a line: 无论如何,您的代码只是缺少一行:
add([],[]).
add([H1|T1],[H2|T2]) :-
is(H2,+(H1,1)), T1=T2;
is(H2,+(H1,2)), T1=T2;
H1=H2, add(T1,T2).
After comment, here is how to subtract and keep only positive values: 评论后,以下是仅减去和保留正值的方法:
add([H1|T1],[H2|T2]) :-
H2 is H1-1, H2 > 0, T1=T2;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.