|
The Prolog Tutorial: Input / Output |
|
By this stage of the tutorial you should be able to create simple procedures and know a number of the built-in predicates in Prolog.
|
|
The aims of this tutorial
Basic Input and Output So far we have come across two input and output predicates, write/1 and read/1. To recap write will print a Prolog term onto the screen and read will get input from the user so long as the user enters a legitimate Prolog term. These predicates can also be used to read from a file and write to a file. Type the following at the prompt and see what response you get. | ?- seeing( X ). | ?- telling( X ). In both case you should have got a response that said X = user. The first predicate, seeing/1, gives the current name of the input stream. In this case your keyboard. The second predicate, telling/1, gives the name of the current output stream. The default is the screen. By using the predicates, see/1 and tell/1 we can change these defaults. For example type the following - | ?- see( 'family_tree.pl' ). | ?- seeing( X ). The input stream has moved from the keyboard to the file. Now type the following - | ?- read( X ). Repeat this last query a few times and see what response you get. You should notice that read is now gathering input from the file. X is instantiated to the next Prolog term in the file every time we call it. Now type the following - | ?- seen. | ?- seeing( X ). What has happened here? The predicate seen/0 closes the current input stream and sets it back to the default, the keyboard. Now try the following - | ?- tell( 'test_output.pl' ). | ?- telling( X ). | ?- nl, write( 'male( bob ).' ), nl. | ?- told. | ?- telling( X ). In this interaction you have moved the output stream to a file called 'test_output.pl', if this file does not exist it will be created. This change in the output stream can be checked by using telling/1. You now use write/1 to enter a fact into this file. After that has been done you have used told/0 to close the current output stream and return it to the default, the screen.
Exercise As an exercise you should attempt to 'read' the fact you have placed in 'test_output.pl' by using the predicates you have just learned.
You should note from all this the predicates write/1 and read/1 are quite powerful. There are not the only predicates for input / output. Here are some more that may prove useful. get - get( X ) will read the next character from the standard input device, skipping non-printing characters and instantiates X to its ASCII code value. get0 - same as 'get' but doesn't skip non-printing characters. put - put( X ) will write the character of ASCII code X to the standard output.
What you should have learned from this tutorial -
The built-in predicates that were first introduced in this tutorial were: see/1, tell/1, seeing/1, telling/1, seen/0, told/0, get/1, get0/1, put/1 |
|
Author - Jer Hayes - 2000 |