Prolog:编写一个打印“Hello World”的过程

12

我想将这个简单的东西加载到我的编辑器中:

Write:-repeat,write("hi"),nl,fail.

怎样才能使它打印“hi”?

我目前正在尝试进行文件->新建操作

并将文件保存在E:\Program Files\pl\xpce\prolog\lib中命名为Write

执行查询:

?-Write.

它会打印:

"hi"。

1 ?- Write.
% ... 1,000,000 ............ 10,000,000 years later
% 
%       >> 42 << (last release gives the question)

为什么?


3
顺便提一下,“错误信息”是指《银河系漫游指南》中的一个参考。 - tloflin
4
我知道。我喜欢那些书,但是我觉得那个信息非常愚蠢。这是一个强行而晦涩的笑话。 - andandandand
2个回答

10

编辑

我进行了更多的研究。显然,当你向SWI-Prolog询问一个未实例化的变量时,它会这样做。

$ prolog
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.6.64)
Copyright (c) 1990-2008 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

?- X.
% ... 1,000,000 ............ 10,000,000 years later
% 
%       >> 42 << (last release gives the question)
?- 

更新

将名称改为小写字母可以解决问题。大写字母用于变量:

helloworld.prolog:

helloworld:-write('Hello World!'),nl,fail.

那么:

$ prolog
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.6.64)
Copyright (c) 1990-2008 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

?- ['helloworld.prolog'].
% helloworld.prolog compiled 0.00 sec, 1,376 bytes
true.

?- helloworld.
Hello World!
false.

?- 

请注意,您必须先查阅该文件。我试过了,它确实有效。


我不这么认为,我把程序改成了Write:-write(“hi”),但它仍然做着同样的事情。 - andandandand
好的,我该如何打印任何东西?我想做一个简单的“hello world”。 - andandandand
你不能以大写字母开头定义一个过程。请将你的代码更改为 hello_world:-write('hello world'),nl,fail. 注意,我是以小写字母开头定义这个过程的。 - Vivin Paliath
你把helloworld.prolog保存在哪个目录下?为什么使用.prolog扩展名?我的SWI只能识别扩展名为.pl的文件。 - andandandand
在我调用 prolog 的同一目录中。我使用 .prolog 作为任意扩展名。SWI Prolog 没有抱怨。你可以将其更改为 .pl,它应该仍然可以工作。 - Vivin Paliath

3
你需要将过程命名为write,而不是Write。大写字母开头用于变量。(如果你将其命名为其他名称,比如writeHi,那么它就不会与内置过程同名,这样可能会更清晰一些,但当你调用它时,它仍然可以使用write,因为你的write与内置过程具有不同的元数)。
此外,你可能想要将"hi"替换为'hi',尽管两种方式都可以工作(但只有第二种版本实际上会将单词“hi”打印到屏幕上,你的版本将其作为整数列表打印)。

我改了子句为writehello:-write("hi").,现在输出是:ERROR: Undefined procedure: writehello/0。我认为问题在于我保存子句的物理位置。顺便说一下,我不确定但我认为把它称作“clause”比“procedure”更正确。 - andandandand
@dmindreader:在尝试调用之前,您必须加载(consult)文件。我保证它使用小写名称可以正常工作。我实际上已经尝试过了。 - sepp2k

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接