在数组中设置值 - Prolog
我有一些 set_value_in_array 的规则。 他是用Val替换Array[J]中的值。
set_value_in_array([], _, _, _, _).
set_value_in_array([Head | Array], Val, J, AccJ, NewArray) :-
AccJ = J,
NewAccJ is AccJ + 1,
set_value_in_array(Array, Val, J, NewAccJ, [Val | NewArray])
;
NewAccJ is AccJ + 1,
set_value_in_array(Array, Val, J, NewAccJ, [Head | NewArray]).
-----------------------------
-----------------------------
% execute in terminal
?- set_value_in_array([1,2,3], 10, 1, 0, NewArray).
true ;
true.
为什么 set_value_in_array 不将 NewArray 显示为 [1, 10, 3]? 他总是回归真实。
更新:
当我这样做时 set_value_in_array([], Val, J, AccJ, NewArray) :- write(NewArray)。 他正在返回一些看起来正确的解决方案
?- set_value_in_array([1,2,3,4,5,6],100,1,0,X).
[6, 5, 4, 3, 100, 1|_G516]
true.
,但是如何使其在没有 write 函数的情况下工作呢?
I have some rule which set_value_in_array.
He is repalce value in Array[J] by Val.
set_value_in_array([], _, _, _, _).
set_value_in_array([Head | Array], Val, J, AccJ, NewArray) :-
AccJ = J,
NewAccJ is AccJ + 1,
set_value_in_array(Array, Val, J, NewAccJ, [Val | NewArray])
;
NewAccJ is AccJ + 1,
set_value_in_array(Array, Val, J, NewAccJ, [Head | NewArray]).
-----------------------------
-----------------------------
% execute in terminal
?- set_value_in_array([1,2,3], 10, 1, 0, NewArray).
true ;
true.
Why set_value_in_array NOT show NewArray as [1, 10, 3]?
He is always return true.
Update:
When I do
set_value_in_array([], Val, J, AccJ, NewArray) :- write(NewArray).
He is return something looks to right solution
?- set_value_in_array([1,2,3,4,5,6],100,1,0,X).
[6, 5, 4, 3, 100, 1|_G516]
true.
But how to make it work without write function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码的主要问题是您没有正确构造结果。应该是相反的:
代码还存在其他几个问题。一般来说,当您删除列表的第一个元素时,您应该仔细考虑较小的情况是什么,以及基本情况是什么(ypou 不在那里指定结果列表)。
您还需要为第二种情况指定
AccJ \== J
。The main problem with your code is that you don't construct the result correctly. It should be the other way round:
There are also several other problems with the code. In general you should think carefully what the smaller cases are when you remove the first element of the list, and what the base case is (ypou don't specify the result list there).
You also need to specify that
AccJ \== J
for the second case.