In console applications it is often desirable to ask the user a question, the following example asks the user a question and expects a yes or no answer. If something else is entered the question is asked again.
| %Ask a yes-no question, if the user answered yes then Result
is unified with the %atom 'yes', if the user answered no then Result is unified with 'no', else the %question is asked again ask_question_yn(Msg, Result) :- repeat, nl, write( Msg ), write(' y/n ?'), read( N ), ( (member(N, ['y', 'Y', 'yes', 'Yes', 'YES']), !, (Result = yes), nl) ; (member(N, ['n', 'N', 'no', 'No', 'NO']), !, (Result = no), nl) ). |
The built-in predicate repeat/0 is used to ask the question again if the user did not enter a term which unifies with yes, no or a term equal to yes or no. The complete source of this example is located in the file 'examples\console\calcform.txt' of the Trinc-Prolog program folder.
This example is located in the file examples\streams\extract.txt. It opens a file as a text file and then uses get_char/2 to get the next character from the input stream. To detect if the end of the stream was reached the unifiable operator is used. The stream is closed if the current position of the stream is end-of-stream, at_end_of_stream/1 succeeds then.
| extract_chars( Input ) :- open(Input, read, I, [alias(in)]), extract_ch(I). extract_ch( Stream ) :- get_char(Stream, C), C \= end_of_file, extract_ch(Stream). extract_ch( Stream ) :- at_end_of_stream(Stream), close(Stream). |
This example is located in the file examples\streams\write.txt. The program opens a single input stream and three output streams. A complete Prolog term is read from the input stream by the built-in predicate read/2 and the term is then written to each of the three output streams. For each output stream a different version of write is used (write_canonical, writeq). To write a valid Prolog term to an output stream it is necessary, after writing the term, to write the closing dot of the term. A newline character is written to each of the output streams by nl/1.
| start( Input, Output, Output2, Output3 ) :- open(Input, read, I, [alias(input_stream)]), open(Output, write, O, [alias(output_stream)] ), open(Output2, write, O2, [alias(output_stream2)] ), open(Output3, write, O3, [alias(output_stream3)] ), process_all(I, O, O2, O3). process_all( In, Out, Out2, Out3 ) :- read(In, Term), Term \= end_of_file, write(Out, Term), write(Out, .), nl(Out), write_canonical(Out2, Term), write(Out2, .), nl(Out2), writeq(Out3, Term), write(Out3, .), nl(Out3), not (at_end_of_stream(In)), process_all(In, Out, Out2, Out3). process_all( In, Out, Out2, Out3 ) :- at_end_of_stream(In), close(In), close(Out), close(Out2), close(Out3). |