Prolog Program Style (ch. 8) Many style issues are applicable to any program in any language. Many style issues are applicable to any program in any language.

Slides:



Advertisements
Similar presentations
Adapted from Scott, Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
Advertisements

Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
Overview of Data Structures and Algorithms
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
Names and Bindings.
Prolog OR (disjunction) “;” is same as a logical OR “;” is same as a logical OR It is also equivalent to using separate clauses... It is also equivalent.
Chapter 3 Loaders and Linkers
Practice Quiz Question
CompSci Searching & Sorting. CompSci Searching & Sorting The Plan  Searching  Sorting  Java Context.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages It’s elegant, minimal, can be.
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
1 Foundations of Software Design Fall 2002 Marti Hearst Lecture 18: Hash Tables.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Controlling Backtracking Notes for Ch.5 of Bratko For CSCE 580 Sp03 Marco Valtorta.
Programming Language Paradigms: summary. Object-oriented programming Objects are the fundamental building blocks of a program. Interaction is structured.
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
Tirgul 8 Universal Hashing Remarks on Programming Exercise 1 Solution to question 2 in theoretical homework 2.
Run-Time Storage Organization
Run time vs. Compile time
CS 206 Introduction to Computer Science II 04 / 29 / 2009 Instructor: Michael Eckmann.
CS1104 Assembly Language: Part 1
CS 206 Introduction to Computer Science II 12 / 10 / 2008 Instructor: Michael Eckmann.
27-Jun-15 Profiling code, Timing Methods. Optimization Optimization is the process of making a program as fast (or as small) as possible Here’s what the.
Introduction and Syntax. Course objectives Discuss features of programming languages. Discuss how the features are implemented in a simple computer architecture.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
1 ES 314 Advanced Programming Lec 2 Sept 3 Goals: Complete the discussion of problem Review of C++ Object-oriented design Arrays and pointers.
1.3 Executing Programs. How is Computer Code Transformed into an Executable? Interpreters Compilers Hybrid systems.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
Formal Models of Computation Part II The Logic Model
FATIH UNIVERSITY Department of Computer Engineering Controlling Backtracking Notes for Ch.5 of Bratko For CENG 421 Fall03.
CS 403: Programming Languages Lecture 2 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
MIPS coding. SPIM Some links can be found such as:
Types for Programs and Proofs Lecture 1. What are types? int, float, char, …, arrays types of procedures, functions, references, records, objects,...
COSC 2P93 Logic Programming Instructor: Brian Ross Instructor: Brian Ross Texts: Texts: Prolog Programming for Artificial Intelligence,4e, Ivan Bratko,
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
1 Names, Scopes and Bindings Aaron Bloomfield CS 415 Fall
CSc 453 Runtime Environments Saumya Debray The University of Arizona Tucson.
Sorting with Heaps Observation: Removal of the largest item from a heap can be performed in O(log n) time Another observation: Nodes are removed in order.
Functions and Procedures. Function or Procedure u A separate piece of code u Possibly separately compiled u Located at some address in the memory used.
1 ENERGY 211 / CME 211 Lecture 26 November 19, 2008.
Declarative vs Procedural Programming  Procedural programming requires that – the programmer tell the computer what to do. That is, how to get the output.
14/10/04 AIPP Lecture 7: The Cut1 Controlling Backtracking: The Cut Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 7 14/10/04.
F28PL1 Programming Languages Lecture 16: Prolog 1.
Chapter 8 – Main Memory (Pgs ). Overview  Everything to do with memory is complicated by the fact that more than 1 program can be in memory.
15/11/04 AIPP Lecture 14: Database Manipulation1 Database Manipulation Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 14 15/11/04.
Chapter 6 Programming Languages (1) Introduction to CS 1 st Semester, 2015 Sanghyun Park.
B. Ross Cosc 4f79 1 Inference mechanisms Backward chaining - goal-driven reasoning which gathers data as needed - Prolog's default mechanism - good for.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 9.
1 Prolog and Logic Languages Aaron Bloomfield CS 415 Fall 2005.
Lecture by: Prof. Pooja Vaishnav.  Language Processor implementations are highly influenced by the kind of storage structure used for program variables.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Bindings. Typical stages of program execution First, the program is compiled Then everything is loaded into memory Then it is linked to any library routines.
Concepts of programming languages Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil 1-1.
CS 152: Programming Language Paradigms March 19 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Compiler Directives. The C Preprocessor u The C preprocessor (cpp) changes your source code based on instructions, or preprocessor directives, embedded.
C LANGUAGE Characteristics of C · Small size
Intro To Algorithms Searching and Sorting. Searching A common task for a computer is to find a block of data A common task for a computer is to find a.
CS 150: Analysis of Algorithms. Goals for this Unit Begin a focus on data structures and algorithms Understand the nature of the performance of algorithms.
In The Name Of Allah Lab 03 1Tahani Aldweesh. objectives Searching for the solution’s. Declaration. Query. Comments. Prolog Concepts. Unification. Disjunction.
From Conventional Languages to Prolog –What we can do in conventional languages but not in Prolog –What we can do in Prolog but not in conventional languages.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
Introduction to Exceptions in Java CS201, SW Development Methods.
Logic Programming Lecture 2: Unification and proof search.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
Runtime support for region-based memory management in Mercury
COSC 2P93 Prolog: Debugging
Tail Recursion.
Algorithm design and Analysis
Presentation transcript:

Prolog Program Style (ch. 8) Many style issues are applicable to any program in any language. Many style issues are applicable to any program in any language. Some Prolog specifics: Some Prolog specifics: short clauses, predicates short clauses, predicates If meaning in comments must use “and”, then break into separate preds. If meaning in comments must use “and”, then break into separate preds. meaningful names for predicates, constants, variables meaningful names for predicates, constants, variables helps programmer understand the meaning of their code helps programmer understand the meaning of their code good indentation good indentation use the same conventions throughout program use the same conventions throughout program cuts: use green cuts rather than red cuts: use green cuts rather than red if possible, use not, one, -> instead of cuts if possible, use not, one, -> instead of cuts try to avoid assert/retract unless absolutely required try to avoid assert/retract unless absolutely required be careful to restore program state (database) when necessary be careful to restore program state (database) when necessary comments: comments: I/O convention of predicates I/O convention of predicates essentials of algorithm essentials of algorithm special features, shortcomings, assumptions about input,... special features, shortcomings, assumptions about input,...

Efficiency issues Declarative vs procedural Declarative vs procedural a difficult balance: clearest solutions can be the most inefficient a difficult balance: clearest solutions can be the most inefficient sometimes must encode a clear solution efficiently, using procedural considerations sometimes must encode a clear solution efficiently, using procedural considerations Algorithm vs implementation Algorithm vs implementation a quicksort is faster than a bubble sort, no matter how you implement it! a quicksort is faster than a bubble sort, no matter how you implement it! A fast algorithm can be implemented inefficiently, however. A fast algorithm can be implemented inefficiently, however. Data structures Data structures related to algorithms related to algorithms a better data structure can naturally result in a faster implementation a better data structure can naturally result in a faster implementation eg. a sorted binary tree permits faster data extraction than an unsorted linear list eg. a sorted binary tree permits faster data extraction than an unsorted linear list Nondeterminism vs determinism Nondeterminism vs determinism reduce backtracking: avoid needless searching: once, if-then-else, cuts reduce backtracking: avoid needless searching: once, if-then-else, cuts Backtracking requires extra memory. Backtracking requires extra memory. consult vs compile consult vs compile depending on implementation, compiling programs can give upwards of a 10x speed increase depending on implementation, compiling programs can give upwards of a 10x speed increase (lose debugging info, however) (lose debugging info, however)

Memory and recursion recursion requires memory recursion requires memory stack used to save tree for return stack used to save tree for return extra usage for backtracking... extra usage for backtracking... p(...) :- do_things(...), % Memory used here to do_more_things(...), % save tree for backtracking. do_more_things(...), % save tree for backtracking. p(...). % Recursion. This is an examples of tail recursion: last goal is recursive call, and goals before it are deterministic (backtracking will fail). This is an examples of tail recursion: last goal is recursive call, and goals before it are deterministic (backtracking will fail). To optimize, do this: To optimize, do this: p(...) :- do_things(...), do_more_things(...), do_more_things(...), !, % This throws away tree before call. p(...). % Recursion.

Efficiency: memory This can still cause problems in very large computations. Sometimes, various memory usage before the cut can be enormous. This can still cause problems in very large computations. Sometimes, various memory usage before the cut can be enormous. Some Prologs such as Sicstus have a builtin memory management optimizer called “garbage_collect” Some Prologs such as Sicstus have a builtin memory management optimizer called “garbage_collect” garbage collection important for symbolic languages (and Java!): finds unused memory (eg. unused atoms, freed clauses, etc.), and puts it back on heap for later usage garbage collection important for symbolic languages (and Java!): finds unused memory (eg. unused atoms, freed clauses, etc.), and puts it back on heap for later usage done automatically at periodic times. Unfortunately, might not happen when required! done automatically at periodic times. Unfortunately, might not happen when required! calling garbage_collect lets programmer ensure of optimal memory use calling garbage_collect lets programmer ensure of optimal memory use p(...) :- do_things(...), garbage_collect, do_more_things(...), do_more_things(...),garbage_collect, !, % this throws away tree before call p(...). % recursion

Last-clause determinacy Sicstus compiler will automatically “insert” a cut into the first goal of the last clause of a recursive predicate. Sicstus compiler will automatically “insert” a cut into the first goal of the last clause of a recursive predicate. So this is not required... So this is not required... p(...) :-... p(...) :- % last clause of p. !, %  unnecessary! !, %  unnecessary! (do something), p(...). 5COSC 2P93 Prolog: Lisp

Efficiency: execution profiling Profile: run-time execution statistics Profile: run-time execution statistics See sect. 9.2, Sicstus manual See sect. 9.2, Sicstus manual Scheme: Scheme: ?- [Load some code.] ?- prolog_flag(profiling,_,on). ?- [Run some queries.] ?- prolog_flag(profiling,_,off). ?- print_profile.

Profiling insns try/retry called name *13694/14300 user:remove_nth/4 ← callers: remove_nth times *13694/14300 user:remove_nth/4 ← callers: remove_nth times *606/14300 user:select_random/3 ← select_random 606 times *606/14300 user:select_random/3 ← select_random 606 times *14300 user:remove_nth/4 ← remove_nth called times *14300 user:remove_nth/4 ← remove_nth called times *13694/14300 user:remove_nth/4 ← called preds: remove_nth times *13694/14300 user:remove_nth/4 ← called preds: remove_nth times *101/5050 user:lotto649/1 *101/5050 user:lotto649/1 *4949/5050 user:make_intlist/3 *4949/5050 user:make_intlist/ *5050 user:make_intlist/ *5050 user:make_intlist/3 *4949/5050 user:make_intlist/3 *4949/5050 user:make_intlist/ *101/2027 user:lotto_loop/9 *101/2027 user:lotto_loop/9 *1926/2027 user:writelist/1 *1926/2027 user:writelist/ *2027 user:writelist/ *2027 user:writelist/1 *1926/2027 user:writelist/1 *1926/2027 user:writelist/1--etc 7COSC 2P93 Prolog: Lisp

Efficiency: determinism Nondeterminacy: multiple solutions via backtracking Nondeterminacy: multiple solutions via backtracking a major feature of Prolog: search a major feature of Prolog: search also a source of inefficiency when multiple solutions not needed also a source of inefficiency when multiple solutions not needed possible to get erroneous solns on backtracking as well possible to get erroneous solns on backtracking as well Sicstus Prolog indexes clauses based on first argument Sicstus Prolog indexes clauses based on first argument a hash table created, with first arg value as hash key a hash table created, with first arg value as hash key interpreter will very quickly unify a call with its “hashed” clause; no need for unification on inappropriate calls. interpreter will very quickly unify a call with its “hashed” clause; no need for unification on inappropriate calls. But if a clause has a variable 1st arg, this won’t work But if a clause has a variable 1st arg, this won’t work When possible, make predicates determinate When possible, make predicates determinate each clause takes care of one case, given in 1st arg each clause takes care of one case, given in 1st arg Result: Result: faster execution faster execution less memory usage less memory usage

Example: determinism % make integer list... intlist(N, L) :- N > 0, N > 0, make_intlist(0, N, L). make_intlist(0, N, L). make_intlist(M, N, [ ]) :- M > N. M > N. make_intlist(M, N, [M|L2]) :- M =< N, M =< N, M2 is M+1, M2 is M+1, make_intlist(M2, N, L2). make_intlist(M2, N, L2). Notice how 1 st arg to make_intlist/3 is variable. Notice how 1 st arg to make_intlist/3 is variable. So Prolog must use inefficient unification to match calls with clauses. So Prolog must use inefficient unification to match calls with clauses. 9COSC 2P93 Prolog: Lisp

Determinism intlist(N, L) :- N > 0, N > 0, make_intlist(L, 0, N). make_intlist(L, 0, N). make_intlist([ ], M, N) :- M > N. M > N. make_intlist([M|L2], M, N) :- M =< N, M =< N, M2 is M+1, M2 is M+1, make_intlist(L2, M2, N). make_intlist(L2, M2, N). Here, we’ve moved 3 rd arg (solution list) to 1 st position. This version is faster: calls to make_intlist can be resolved instantly using 1 st argument value. 10COSC 2P93 Prolog: Lisp

Determinacy checker command: spdet file_name command: spdet file_name If we call it on “inefficient” make_intlist... If we call it on “inefficient” make_intlist... * Non-determinate: user:make_intlist/3 (clause 1) * Indexing cannot distinguish this from clause 2. spdet –D (file) will also generate declarations to use... spdet –D (file) will also generate declarations to use... :- nondet user:make_intlist/3. 11COSC 2P93 Prolog: Lisp