90 likes | 325 Views
Side effects in Prolog. Lecturer: Xinming (Simon) Ou CIS 505: Programming Languages Fall 2010 Kansas State University. 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
E N D
Side effects in Prolog Lecturer: Xinming (Simon) Ou CIS 505: Programming Languages Fall 2010 Kansas State University
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
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)).
Printing statements • Print a term • e.g. write(‘Hello world’). write(world). write(X). • Print a new line • nl. • writeln(‘abc’). • write(‘\n’).
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]).
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.
Assignment 7 • Use Prolog to implement the interpreter in assignment 2. • memory and environment implemented using dynamic predicates • env(Name, Type, Location).
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.
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’]