Presentation is loading. Please wait.

Presentation is loading. Please wait.

Side effects in Prolog Lecturer: Xinming (Simon) Ou CIS 505: Programming Languages Fall 2010 Kansas State University 1.

Similar presentations


Presentation on theme: "Side effects in Prolog Lecturer: Xinming (Simon) Ou CIS 505: Programming Languages Fall 2010 Kansas State University 1."— Presentation transcript:

1 Side effects in Prolog Lecturer: Xinming (Simon) Ou CIS 505: Programming Languages Fall 2010 Kansas State University 1

2 Side effect When using Prolog as a programming language, it is often needed to create side effects – e.g. printing to the display, writing to files – Some side effect will influence the Prolog execution environment and execution behaviors 2

3 Asserting facts Facts can be loaded into the Prolog database. – e.g. ?- load_dyn(‘input.P’). The predicates defined in input.P are called “dynamic predicates”. – They can be added to the database using the load_dyn command, or the “assert” command – e.g. ?- assert(parent(bill, mary)). – They can be removed from the database using the “retract”, or “retractall” command. – E.g. ?- retract(parent(X,Y)). ?- retractall(parent(X,Y)). 3

4 Printing statements Print a term – e.g. write(‘Hello world’). write(world). write(X). Print a new line – nl. – writeln(‘abc’). – write(‘\n’). 4

5 Cut The cut command “!” will eliminate all the choice points for the parent goal. – e.g. member(A, [A|_As]) :- !. member(A, [_B|Bs]) :- member(A, Bs). – But this will break the declarative semantics. Try this: ? – member(A, [1,2,3]). 5

6 Negation in Prolog Negation by failure: – not L succeeds if L fails. – It is equivalent to: not(L) :- L, !, fail. not(L). Negation by failure is not logical negation, when the literal contains variables when the negation is called. 6

7 Assignment 7 Use Prolog to implement the interpreter in assignment 2. memory and environment implemented using dynamic predicates – env(Name, Type, Location). 7

8 Memory The memory is a mapping from locations to values. The memory/2 predicate provides the mapping. – memory(Location, Value). – memoryCounter(Length) returns the number of cells in the memory. – memoryAppend(Value) add a new memory cell and put Value into it. – memoryUpdate(Location, Value) updates the memory location with the value. 8

9 Environment Provides mapping from a variable name to its type and memory location that holds the value. – env(name, type, value) provides the mapping type is either [‘int’] or [‘ptr’, ‘int’] 9


Download ppt "Side effects in Prolog Lecturer: Xinming (Simon) Ou CIS 505: Programming Languages Fall 2010 Kansas State University 1."

Similar presentations


Ads by Google