Docsity

Prolog I/O and Cuts: Lecture Notes for CPSC 326 (Spring 2013), Study notes of Programming Languages

Partial preview of the text

Download Prolog I/O and Cuts: Lecture Notes for CPSC 326 (Spring 2013) and more Study notes Programming Languages in PDF only on Docsity!

Today ...

  • Prolog I/O and cuts

Basic Prolog I/O

Output

  • The predicate write(+Term) prints Term

?- write(hi). hi true.

?- write(’Hello World!’). Hello World! true.

?- write(’Hello’), nl, write(’World!’). Hello World! true.

Input

  • The opposite of write is read(-Term)

?- read(X). |: hello. % |: is the default read prompt X = hello.

?- read(X). |: ’Hello World!’. % Must be quoted here X = ’Hello Word!’.

  • Can set the prompt

?- prompt(_, ’> ’). % first arg is old prompt true.

?- read(X).

hi. X = hi.

  • Can also just use write ...

?- write(’Please enter something: ’), read(X). Enter somthing: hi. X = hi.

Prolog supports various other I/O operations as well

  • Reading and writing files (open, write)
  • Reading characters, numbers, etc. (e.g., get)

Prolog makes some I/O tasks easy

  • Like checking for valid input

menu_choice(X) :- write(’Enter a choice (1 to 4): ’), read(X), member(X, [1,2,3,4]).

Instead, use the Prolog cut (!) operator

  • Forces Prolog to stop searching for alternatives when an answer is found
    • A cut “burns backtracking bridges”
    • once executed, commits to the current solution
    • eliminates backtracking options

A very simple example

a :- b, c. a :- d. b. c. d.

Q: What is the proof tree for solve[a]?

?- a. true ; true.

  • a is proved twice!

Now lets add a cut ...

a :- b, !, c. a :- d. b. c. d.

solve [a]

solve [b,!,c]

nothing nothing^ solve [!,c]

solve [c]

nothing nothing nothing solve []^ nothing

  • We end up only proving a once ...
    • The path to the cut is “frozen”
    • We won’t try different solutions for b or a
    • We will still try different solutions for c

We could also rewrite this as(∗):

member(X, [X|_]). member(X, [H|T]) :- + (X=H), member(X, T).

Q: But can you see a possible problem using this or cuts?

  • What if we wanted to find all members of a list?

Q: For example, what will member(X, [1, 2]) return?

  • Only the first element!

(∗) (^) In fact, + is defined using a cut:

+(P) :- call(P), !, fail. +(P).