How to Run Prolog

De Augusto Baffa Wiki
Revisão de 11h00min de 28 de dezembro de 2020 por Abaffa (discussão | contribs) (Criou página com '3. The goal here, 'factorial(10,What)', essentially says "the factorial of 10 is What?". The word 'What' begins with an upper-case letter, denoting a logical variable. Prolog...')
Ir para navegação Ir para pesquisar
Outros idiomas:
English • ‎português do Brasil

The examples in this Prolog Tutorial were developed using either Quintus Prolog running on Digital Equipment Corporation MicroVAXes (ancient history) or using SWI Prolog on either Sun Sparks (long ago), in Windows on a PC (a while ago), or (recently) under the OS X operating system on a Mac.

Other important prolog systems (Borland, XSB, LPA, Minerva ...) have been used for development and testing over the past 25 years. A new section of this tutorial is planned to describe prolog systems in a general way, but that section is not available at this time.

SWI-Prolog's website has lots of information about SWI-Prolog, a download area, and documentation. The upkeep for SWI-Prolog is excellent. The link ...

The examples in this tutorial use a simplified form of interaction with a typical Prolog interpreter. The sample programs should execute similarly on any system using an Edinburgh-style Prolog interpreter or interactive compiler.

To start an interactive SWI-Prolog session under Unix, open a terminal window and type the approprite command (indicated in the installation instructions). For example, on our Mac this is ...

$ /opt/local/bin/swipl

{We never type that last line: we employ Unix source files to start SWI-Prolog using additional command line arguments and/or switches for special purposes. The reader could explore this possibility soon after learning more prolog basics.}

Under Windows, SWI-Prolog installs a start icon that can be double-clicked to initiate the interpreter. The interpreter then starts in its own command window.

A startup message or banner may appear, and that will soon be followed by a goal prompt looking similar to the following

?- _


Interactive goals in Prolog are entered by the user following the '?- ' prompt.

Many Prologs have command-line help information. SWI Prolog has extensive help information. This help is indexed and guides the user. To learn more about it, try

?- help(help).

Notice that all of the displayed symbols need to be typed in, followed by a carriage return.

To illustrate some particular interactions with prolog, consider the following sample session. Each file referred to is assumed to be a local file in the user's account, which was either created by the user, obtained by copying directly from some other public source, or obtained by saving a text file while using a web browser. The way to achieve the latter is either to follow a URL to the source file and then save, or to select text in a Prolog Tutorial web page, copy it, paste into a text editor window and then save to file. The comments /* ... */ next to goals are referred to in the notes following the session.

?- ['2_1.pl'].           /* 1. Load a program from a local file*/  
yes  
?- listing(factorial/2). /* 2. List program to the screen*/  
  
factorial(0,1).
  
factorial(A,B) :-  
           A > 0, 
           C is A-1,
           factorial(C,D),
           B is A*D. 
yes
  
?- factorial(10,What).     /* 3. Compute factorial of 10 */
What=3628800
 
?- ['2_7.pl'].            /* 4. Load another program */

?- listing(takeout).
  
takeout(A,[A|B],B).
takeout(A,[B|C],[B|D]) :-
          takeout(A,C,D).
yes

?- takeout(X,[1,2,3,4],Y).  /* 5. Take X out of list [1,2,3,4] */
X=1  Y=[2,3,4] ;              Prolog waits ... User types ';' and Enter
X=2  Y=[1,3,4] ;               again ...  
X=3  Y=[1,2,4] ;               again ...
X=4  Y=[1,2,3] ;               again ...
no                             Means: No more answers.

?- takeout(X,[1,2,3,4],_), X>3.  /* 6.  Conjunction of goals */
X=4 ;
no

?- halt.                         /* 7. Return to OS */

The comments appearing at the right at various spots in a sample session were added with a text processor. They also serve as reference signposts for the notes which appear below. We discuss several points now, while other details will be deferred to later sections.


Notes

1. A Prolog goal is terminated with a period "." In this case the goal was to load a program file. This "bracket" style notation dates back to the first Prolog implementations. Several files can be chain loaded by listing the filenames sequentially within the brackets, separated by commas. In this case, the file's name is 2_1.pl (programs corresponding to Section 7.1 of this tutorial), which contains two prolog programs for calculating the factorial of a positive integer. The actual program in the file is discussed in Section 2.1. The program file was located in the current directory. If it had not been, then the path to it would have to have been specified in the usual way.

1. A Prolog goal is terminated with a period "." In this case the goal was to load a program file. This "bracket" style notation dates back to the first Prolog implementations. Several files can be chain loaded by listing the filenames sequentially within the brackets, separated by commas. In this case, the file's name is 2_1.pl (programs corresponding to Section 7.1 of this tutorial), which contains two prolog programs for calculating the factorial of a positive integer. The actual program in the file is discussed in Section 2.1. The program file was located in the current directory. If it had not been, then the path to it would have to have been specified in the usual way.

3. The goal here, 'factorial(10,What)', essentially says "the factorial of 10 is What?". The word 'What' begins with an upper-case letter, denoting a logical variable. Prolog satisfies the goal by finding the value of the variable 'What'.

4. Ambos os "programas" agora residem na memória, dos dois arquivos de origem 2_1.pl e 2_7.pl. O arquivo 2_7.pl contém muitas definições de processamento de lista. (Consulte a Seção 2.7.)

5. No programa que acabou de carregar, está uma definição do predicado lógico 'takeout'. O objetivo 'takeout (X, [1,2,3,4], Y)' pede que X seja retirado da lista [1,2,3,4], deixando a lista restante Y, de todas as maneiras possíveis. Existem quatro maneiras de fazer isso, conforme mostrado na resposta. O predicado 'takeout' é discutido na Seção 2.7. Observe, no entanto, como Prolog é estimulado a produzir todas as respostas possíveis: Depois de produzir cada resposta, Prolog espera com um cursor no final da resposta. Se o usuário digitar um ponto-e-vírgula ';' , O Prolog procurará uma próxima resposta e assim por diante. Se o usuário apenas pressionar Enter, o Prolog para de procurar respostas.

6. Um objetivo composto ou conjuntivo exige que dois objetivos individuais sejam satisfeitos. Observe a meta aritmética (relação interna), 'X> 3'. O Prolog tentará satisfazer esses objetivos na ordem da esquerda para a direita, da mesma forma que eles seriam lidos. Nesse caso, há apenas uma resposta. Observe o uso de uma variável anônima '_' no objetivo, para o qual nenhuma ligação é relatada ("variável irrelevante").

7. O objetivo 'halt' sempre é bem-sucedido e retorna o usuário ao sistema operacional.


Veja Também