SWI-Prolog用户输入和操作

时间:2017-10-20 15:40:42

标签: prolog

我目前正在学习在Prolog中编程,并正在进行一项涉及大小为n的世界的任务,并且根据用户想要移动它的位置拾取和移动3个块。我有一个程序的基本裸骨结构,但是,我遇到的问题是获取用户的输入,存储世界大小的整数并在整个程序中使用变量。我设法获得用户输入,但是当我在代码中的其他地方使用它时,值不是它应该是什么。

例如。如果我为n输入14,然后在position子句输出大小,我得到World Size: _6324而不是14.这似乎导致我的代码中的其他问题,我无法弄清楚如何解决这个问题。我做错了什么,怎么解决这个问题?另外,_6324是什么意思?

这是初始代码,要求用户输入并输出当前数据集,包括世界大小:

%Setting world: world of lenght n, block size of 3
:-assert(at(a,0)).
:-assert(at(b,2)).
:-assert(at(c,5)).


%Gets the initial size of the world from the user
start :- write('What the world length?: '), read(Length), 
         assert(world_length(Length)), nl, position.


%outputs the initial positions of each block
position:- write("Initial Positions: "),nl,
  write('World Size: '), write(Length),nl,
  at(a,X), write(a), write(' is at position '), write(X),nl,
  at(b,Y), write(b), write(' is at position '), write(Y),nl,
  at(c,Z), write(c), write(' is at position '), write(Z),nl,nl,
  write('Instructions: To move a block, simply type in move(block, position).'), nl.

1 个答案:

答案 0 :(得分:1)

Length谓词中的逻辑变量position/0不知道Length谓词中的逻辑变量start/0。< / p>

在Prolog中,没有动态嵌套的范围。

您可以通过调用assert(world_length(Length))谓词中的start/0将此值保存在动态数据库中,这样您就可以在position/0内查询

      write('World Size: '), world_length(Length), write(Length), nl, ...

没有查询,你拥有的是一个未初始化的,尚未设置的逻辑变量Length,而_6432(或_G12345)是它的名字,即打印在这种情况下write。意思是,&#34;没有价值&#34;

相关问题