开发者

Hello world in Prolog

开发者 https://www.devze.com 2023-01-13 00:23 出处:网络
I\'m tearing my hair out trying to find how to just write a Hello World program in Prolog.I just want to create a program that runs like so:

I'm tearing my hair out trying to find how to just write a Hello World program in Prolog. I just want to create a program that runs like so:

> ./hw
Hello, world!
>

The problem is that every single example I can find works in a REPL, like so:

?- consult(hello_world).
% hello compiled 0.00 sec, 612 bytes

Yes
?- hello开发者_如何转开发_world.
Hello World!

Yes

This is the same even with examples of compiled Prolog: the program still just drops into a REPL. This is obviously not much use for a "general-purpose" language. So, how do I write the traditional Hello World?


Using GNU Prolog:

$ cat hello.pl 
:- initialization(main).
main :- write('Hello World!'), nl, halt.

$ gplc hello.pl $ ./hello
Hello World!


You can write your source file to both launch the Prolog interpreter and to quit it when your code is done running. Here is an example using SWI-Prolog:

#!/usr/bin/swipl -q -t hello_world -f

hello_world :- write('Hello World'), nl, 
               halt.

Assuming you put this in a file named 'hw', and set the executable permission, you can call it like you want to:

$ ./hw
Hello World
$


Prolog is not really a general purpose language. We use it to design artificial intelligence systems at university.

You'd have to define a fact, that answers "hello world".

hello('hello world').

Then, inquire the fact:

?- hello(X).

However, depending on the PROLOG compiler, you probably have a write() rule, that you could use:

?- write('hello world'), nl.


writeln('hello world').
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号