Logic Programming: Recursion, lists, data structures

Size: px
Start display at page:

Download "Logic Programming: Recursion, lists, data structures"

Transcription

1 O Y Logic Programming: ecursion, lists, data structures Alan maill ep Alan maill Logic Programming: ecursion, lists, data structures ep /28

2 oday Y ecursion proof search practical concerns List processing Programming with terms as data structures. Alan maill Logic Programming: ecursion, lists, data structures ep /28

3 ecursion Y o far the rules we have seen have been (mostly) non-recursive. his is a limit on what can be expressed. Without recursion, we cannot define transitive closure eg define ancestor/2 in terms of parent/2. Alan maill Logic Programming: ecursion, lists, data structures ep /28

4 ecursion ctd Y n recursive use, the same predicate is used in the head (lhs) of the rule as in the body (rhs) (in the second clause below): ancestor(x,y) :- parent(x,y). ancestor(x,y) :- parent(x,z), ancestor(z,y). Alan maill Logic Programming: ecursion, lists, data structures ep /28

5 ecursion ctd Y n recursive use, the same predicate is used in the head (lhs) of the rule as in the body (rhs) (in the second clause below): ancestor(x,y) :- parent(x,y). ancestor(x,y) :- parent(x,z), ancestor(z,y). his is a fine declarative description of what it is to be an ancestor. ut watch out for the traps!!! Alan maill Logic Programming: ecursion, lists, data structures ep /28

6 eminder: depth-first search Y Prolog searches depth-first in program order ( top to bottom ): egardless of context... even if there is an obvious solution elsewhere in the search space. Alan maill Logic Programming: ecursion, lists, data structures ep /28

7 eminder: depth-first search Y Prolog searches depth-first in program order ( top to bottom ): egardless of context... even if there is an obvious solution elsewhere in the search space. p :- p. p.?- p. the query will loop on the first clause, and fail to terminate. Alan maill Logic Programming: ecursion, lists, data structures ep /28

8 ecursion: order can matter Y ake the program for ancestor/2 with clauses in the opposite order: ancestor(x,y) :- parent(x,z), ancestor(z,y). ancestor(x,y) :- parent(x,y). Alan maill Logic Programming: ecursion, lists, data structures ep /28

9 ecursion: order can matter Y ake the program for ancestor/2 with clauses in the opposite order: ancestor(x,y) :- parent(x,z), ancestor(z,y). ancestor(x,y) :- parent(x,y). his may be less efficient looks for longest path first. More likely to loop if the parent/2 relation has cycles. C: write base cases first (ie non-recursive cases). Alan maill Logic Programming: ecursion, lists, data structures ep /28

10 ule order affects search Y parent(a,b). parent(b,c). ancestor(a,b) parent(a,z),ancestor(z,b) parent(a,b) Z=b ancestor(b,b) Alan maill Logic Programming: ecursion, lists, data structures ep /28

11 ule order affects search Y parent(a,b). parent(b,a). ancestor(a,b) parent(a,z),ancestor(z,b) Z=b ancestor(b,b) parent(b,w),ancestor(w,b) W=a ancestor(a,b). Alan maill Logic Programming: ecursion, lists, data structures ep /28

12 ecursion again Y oal order can matter! ancestor3(x,y) :- parent(x,y). ancestor3(x,y) :- ancestor3(z,y), parent(x,z) Alan maill Logic Programming: ecursion, lists, data structures ep /28

13 ecursion again Y oal order can matter! ancestor3(x,y) :- parent(x,y). ancestor3(x,y) :- ancestor3(z,y), parent(x,z) his returns all solutions, then loops, eg with the following facts: parent(a,b). parent(b,c). Alan maill Logic Programming: ecursion, lists, data structures ep /28

14 oal order affects search Y ancestor3(x,b) parent(x,b) X=a parent(z,b), parent(x,z) Z=a parent(x,a) ancestor3(z,b), parent(x,z) ancestor3(w,b), parent(z,w), parent(x,z) Alan maill Logic Programming: ecursion, lists, data structures ep /28

15 More recursion Y Clause order can matter. ancestor4(x,y) :- ancestor4(z,y), parent(x,z). ancestor4(x,y) :- parent(x,y). Alan maill Logic Programming: ecursion, lists, data structures ep /28

16 More recursion Y Clause order can matter. ancestor4(x,y) :- ancestor4(z,y), parent(x,z). ancestor4(x,y) :- parent(x,y). his will always loop. euristic: put non-recursive goals first. Alan maill Logic Programming: ecursion, lists, data structures ep /28

17 oal order matters Y ancestor4(x,y) ancestor4(x,z),parent(z,y) ancestor4(x,w),parent(w,z),parent(z,y) ancestor(x,),parent(,w),parent(w,z),parent(z,y). Alan maill Logic Programming: ecursion, lists, data structures ep /28

18 ecursion and terms Y erms can be arbitrarily nested xample: unary natural numbers nat(z). nat(s(x)) :- nat(x). Alan maill Logic Programming: ecursion, lists, data structures ep /28

19 ecursion and terms Y erms can be arbitrarily nested xample: unary natural numbers nat(z). nat(s(x)) :- nat(x). o do interesting things, we need recursion. Alan maill Logic Programming: ecursion, lists, data structures ep /28

20 Addition, subtraction Y Addition: add(z,,). add(s(),m,s(p)) :- add(,m,p). Alan maill Logic Programming: ecursion, lists, data structures ep /28

21 Addition, subtraction Y Addition: add(z,,). add(s(),m,s(p)) :- add(,m,p). un in reverse to get all M, that sum to P: Alan maill Logic Programming: ecursion, lists, data structures ep /28

22 Addition, subtraction Y Addition: add(z,,). add(s(),m,s(p)) :- add(,m,p). un in reverse to get all M, that sum to P:?- add(x,y,s(s(s(z)))). X=z,Y=s(s(s(z))); X=s(Z),Y=s(s(z));... Alan maill Logic Programming: ecursion, lists, data structures ep /28

23 Addition, subtraction Y Addition: add(z,,). add(s(),m,s(p)) :- add(,m,p). un in reverse to get all M, that sum to P:?- add(x,y,s(s(s(z)))). X=z,Y=s(s(s(z))); X=s(Z),Y=s(s(z));... se to define leq/2: leq(m,) :- add(m,_,). Alan maill Logic Programming: ecursion, lists, data structures ep /28

24 Addition, subtraction Y Addition: add(z,,). add(s(),m,s(p)) :- add(,m,p). un in reverse to get all M, that sum to P:?- add(x,y,s(s(s(z)))). X=z,Y=s(s(s(z))); X=s(Z),Y=s(s(z));... se to define leq/2: leq(m,) :- add(m,_,). ere _ is a so-called anonymous variable; use to avoid warning of singleton variable in Prolog programs. Can also use, for example, _X, _Anon. Alan maill Logic Programming: ecursion, lists, data structures ep /28

25 Multiplication Y ow define multiplication: multiply(z,,z). % or: multiply(z,_,z). multiply(s(),m,p) :- multiply(,m,q), add(m,q,p). square(,m) :- multiply(,,m). Alan maill Logic Programming: ecursion, lists, data structures ep /28

26 List Processing Y ecall built-in list syntax: list([]). list([x L]) :- list(l). Alan maill Logic Programming: ecursion, lists, data structures ep /28

27 List Processing Y ecall built-in list syntax: list([]). list([x L]) :- list(l). xamples: list append append([],l,l). append([x L],M,[X ]) :- append(l,m,). Alan maill Logic Programming: ecursion, lists, data structures ep /28

28 append in action Y orward direction:?- append([1,2],[3,4],x). X = [1,2,3,4] Alan maill Logic Programming: ecursion, lists, data structures ep /28

29 append in action Y orward direction:?- append([1,2],[3,4],x). X = [1,2,3,4] ackward direction?- append(x,y,[1,2,3,4]). X=[], Y=[1,2,3,4]; X=[1],Y=[2,3,4];... Alan maill Logic Programming: ecursion, lists, data structures ep /28

30 Mode annotations Y hese are recognised ways of indicating properties of Prolog procedures. otation: append(+,+,-) xpect to be called with the first two arguments ground, and third a variable (which we normally expect to bound after the call) Alan maill Logic Programming: ecursion, lists, data structures ep /28

31 Mode annotations Y hese are recognised ways of indicating properties of Prolog procedures. otation: append(+,+,-) xpect to be called with the first two arguments ground, and third a variable (which we normally expect to bound after the call) imilarly, append(-,-,+) Call with last argument ground, first two as variables (which we normally expect to be bound after the call). Alan maill Logic Programming: ecursion, lists, data structures ep /28

32 Mode annotations Y hese are recognised ways of indicating properties of Prolog procedures. otation: append(+,+,-) xpect to be called with the first two arguments ground, and third a variable (which we normally expect to bound after the call) imilarly, append(-,-,+) Call with last argument ground, first two as variables (which we normally expect to be bound after the call). ot code, but often used in annotations? annotation used where any term may appear i.e. ground, variable, or compound term with variables. Alan maill Logic Programming: ecursion, lists, data structures ep /28

33 List Processing ctd Y When is something a member of a list? member(x, [X _]). member(x, [_ ]) :- member(x, ). Alan maill Logic Programming: ecursion, lists, data structures ep /28

34 List Processing ctd Y When is something a member of a list? member(x, [X _]). member(x, [_ ]) :- member(x, ). ypical modes: member(+,+) member(-,+) Alan maill Logic Programming: ecursion, lists, data structures ep /28

35 List processing ctd Y emoving an element of a list: remove(x, [X L], L). remove(x, [Y L], [Y M]) :- remove(x, L, M). Alan maill Logic Programming: ecursion, lists, data structures ep /28

36 List processing ctd Y emoving an element of a list: remove(x, [X L], L). remove(x, [Y L], [Y M]) :- remove(x, L, M). : removes one occurrence of X; fails if X is not a member of the list. ypical mode: remove(+,+,-) Alan maill Logic Programming: ecursion, lists, data structures ep /28

37 List processing ctd Y Zip: pairing of corresponding elements of lists: assumed to be of same length. zip([],[],[]). zip([x L], [Y M], [(X,Y) ]) :- zip(l, M, ). ypical modes: zip(+,+,-). zip(-,-,+). % unzip Alan maill Logic Programming: ecursion, lists, data structures ep /28

38 List flattening Y Write a flatten predicate flatten/2 that iven a list of (lists of... ) Produces a list of individual elements in the original order. Alan maill Logic Programming: ecursion, lists, data structures ep /28

39 List flattening Y Write a flatten predicate flatten/2 that iven a list of (lists of... ) Produces a list of individual elements in the original order. xamples:?- flatten([[1,2],[3,4]], L). L = [1,2,3,4]?- flatten([[1,2],[3,[4,5]],6],l). L = [1,2,3,4,5,6]?- flatten([3,x,[4,5]],l). L = [3,X,4,5] Alan maill Logic Programming: ecursion, lists, data structures ep /28

40 List flattening Y flatten([], []). flatten([ ], M) :- flatten(, f), flatten(, f), append(f, f, M). flatten(x, [X]) :-??? % non-list case; how treat variables?!?! Alan maill Logic Programming: ecursion, lists, data structures ep /28

41 ecords Y Can use terms to define data structures: pb([entry(alan, ),...]). Alan maill Logic Programming: ecursion, lists, data structures ep /28

42 ecords Y Can use terms to define data structures: pb([entry(alan, ),...]). and operations on them: pb_lookup(pb(), P, ) :- member(entry(p,), ). pb_insert(pb(), P,, pb([entry(p,) ])). pb_remove(pb(), P, pb(2)) :- remove(entry(p,_),, 2). Alan maill Logic Programming: ecursion, lists, data structures ep /28

43 rees Y We can define (binary) trees with data (at the nodes). tree(leaf). tree(node( ata, L, )) :- tree(l), tree(). Alan maill Logic Programming: ecursion, lists, data structures ep /28

44 rees Y We can define (binary) trees with data (at the nodes). tree(leaf). tree(node( ata, L, )) :- tree(l), tree(). ata membership in a tree using ; for alternatives in the body of a clause. mem_tree(x, node(x, _, _)). mem_tree(x, node(_, L, )) :- mem_tree(x, L) ; mem_tree(x, ). Alan maill Logic Programming: ecursion, lists, data structures ep /28

45 Preorder traversal Y Pick up the data in a particular order: start at root, traverse recursively left subtree, then right subtree. preorder(leaf, []). preorder(node(x, L, ), [X ]) :- preorder(l, LO), preorder(, O), append( LO, O, ). Alan maill Logic Programming: ecursion, lists, data structures ep /28

46 Preorder traversal Y Pick up the data in a particular order: start at root, traverse recursively left subtree, then right subtree. preorder(leaf, []). preorder(node(x, L, ), [X ]) :- preorder(l, LO), preorder(, O), append( LO, O, ). What happens if we run this in reverse? Alan maill Logic Programming: ecursion, lists, data structures ep /28

47 utorials next week Y he tutorial questions are on the web page; you should work through these before the tutorial. t s recommended to use the sicstus emacs mode to interact with Prolog and edit source code. his mode is invoked automatically when editing Prolog files (with suffix.pl) on C. (ee sicstus documentation if you want to set this up for yourself.) You can find out about the mode by C-h m in emacs when the mode is in use, or via sicstus documentation. Alan maill Logic Programming: ecursion, lists, data structures ep /28

48 Coming Attractions Y on-logical features: xpression evaluation /O cut (pruning proof search) urther reading Learn Prolog ow, ch 3 4 utorial questions on web page. Alan maill Logic Programming: ecursion, lists, data structures ep /28

Chapter 16. Logic Programming. Topics. Unification. Resolution. Prolog s Search Strategy. Prolog s Search Strategy

Chapter 16. Logic Programming. Topics. Unification. Resolution. Prolog s Search Strategy. Prolog s Search Strategy Topics Chapter 16 Logic Programming Summary (resolution, unification, Prolog search strategy ) Disjoint goals The cut operator Negative goals Predicate fail Debugger / tracer Lists 2 Resolution Resolution

More information

Logic Programming: Parsing. Difference Lists, DCGs

Logic Programming: Parsing. Difference Lists, DCGs O Y Logic Programming: Parsing. ifference Lists, Cs Alan maill Oct 15 2015 Alan maill Logic Programming: Parsing. ifference Lists, Cs Oct 15 2015 1/26 oday Y Context ree rammars (review) Parsing in Prolog

More information

CSEN403 Concepts of Programming Languages. Topics: Logic Programming Paradigm: PROLOG Search Tree Recursion Arithmetic

CSEN403 Concepts of Programming Languages. Topics: Logic Programming Paradigm: PROLOG Search Tree Recursion Arithmetic CSEN403 Concepts of Programming Languages Topics: Logic Programming Paradigm: PROLOG Search Tree Recursion Arithmetic Prof. Dr. Slim Abdennadher 8.2.2015 c S. Abdennadher 1 Logic Programming versus Prolog

More information

3 Lists. List Operations (I)

3 Lists. List Operations (I) 3 Lists. List Operations (I) The list is the simplest yet the most useful Prolog structure. A list is a sequence of any number of objects. Example 3.1: L = [1, 2, 3], R = [a, b, c], T = [john, marry, tim,

More information

Logic Programming: Search Strategies

Logic Programming: Search Strategies O Logic Programming: earch trategies Alan maill Oct 19, 2015 Alan maill Logic Programming: earch trategies Oct 19, 2015 1/28 oday Problem representation earch epth irst terative eepening readth irst A/O

More information

Plan of the lecture. G53RDB: Theory of Relational Databases Lecture 14. Example. Datalog syntax: rules. Datalog query. Meaning of Datalog rules

Plan of the lecture. G53RDB: Theory of Relational Databases Lecture 14. Example. Datalog syntax: rules. Datalog query. Meaning of Datalog rules Plan of the lecture G53RDB: Theory of Relational Databases Lecture 14 Natasha Alechina School of Computer Science & IT nza@cs.nott.ac.uk More Datalog: Safe queries Datalog and relational algebra Recursive

More information

Logic Programming: Search Strategies

Logic Programming: Search Strategies O Logic Programming: earch trategies Alan maill ov 5, 2012 Alan maill Logic Programming: earch trategies ov 5, 2012 1/1 oday Problem representation earch epth irst terative eepening readth irst A/O (alternating/game

More information

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog CS 360: Programming Languages Lecture 10: Logic Programming with Prolog Geoffrey Mainland Drexel University Section 1 Administrivia Midterm Tuesday Midterm is Tuesday, February 14! Study guide is on the

More information

The current topic: Prolog. Announcements. Meaning of a Prolog rule. Prolog syntax. Reminder: The deadline for Lab 2 re-mark requests is Friday.

The current topic: Prolog. Announcements. Meaning of a Prolog rule. Prolog syntax. Reminder: The deadline for Lab 2 re-mark requests is Friday. The current topic: Prolog! Introduction! Object-oriented programming: Python! Functional programming: Scheme! Python GUI programming (Tkinter)! Types and values Logic programming: Prolog! Introduction

More information

CS 360: Programming Language Concepts Lecture 15 Logic Programming

CS 360: Programming Language Concepts Lecture 15 Logic Programming Reference: Ch. 12.1-12.5 CS 360: Programming Language Concepts Lecture 15 Logic Programming I. Logic Programming (Generally) What is logic programming? A logic program is a collection of declarations,

More information

Binary Trees, Binary Search Trees

Binary Trees, Binary Search Trees Binary Trees, Binary Search Trees Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search, insert, delete)

More information

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example. Trees, Binary Search Trees, and Heaps CS 5301 Fall 2013 Jill Seaman Tree: non-recursive definition Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every node (except

More information

The Idea Underlying Logic Programming. CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Logic Programming

The Idea Underlying Logic Programming. CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Logic Programming The Idea Underlying CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Department of Computer Science and Engineering University of Minnesota Lectures in Fall

More information

Family Example: Some Facts. respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara).

Family Example: Some Facts. respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara). Family Example: Some Facts respects(barb,dan). respects(barb,katie). respects(dan,brian). respects(dan,barbara). Some Queries?- respects(barb,katie). yes?- respects(barb,x). X=dan; % you type ; and RETURN

More information

CE 221 Data Structures and Algorithms

CE 221 Data Structures and Algorithms CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, 4.1 4.2 Izmir University of Economics 1 Preliminaries - I (Recursive) Definition: A tree is a collection of nodes. The

More information

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge Trees (& Heaps) Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Spring 2015 Jill Seaman 1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root -

More information

Principles of Programming Languages COMP3031: Logic Programming in Prolog

Principles of Programming Languages COMP3031: Logic Programming in Prolog Principles of Programming Languages COMP3031: Logic Programming in Prolog Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China

More information

Week 5 Tutorial Structural Induction

Week 5 Tutorial Structural Induction Department of Computer Science, Australian National University COMP2600 / COMP6260 Formal Methods in Software Engineering Semester 2, 2016 Week 5 Tutorial Structural Induction You should hand in attempts

More information

Chapter 5. Pure PROLOG. Foundations of Logic Programming

Chapter 5. Pure PROLOG. Foundations of Logic Programming Chapter 5 1 Outline vs. logic programming Lists in Adding Arithmetics to Adding the Cut to 2 Syntax of Pure Prolog p(x,a) :- q(x), r(x,yi). p(x, a) q(x), r(x,y i ) % Comment Ambivalent syntax: p(p(a,b),

More information

ADTS, GRAMMARS, PARSING, TREE TRAVERSALS

ADTS, GRAMMARS, PARSING, TREE TRAVERSALS 1 Pointers to material ADS, GRAMMARS, PARSING, R RAVRSALS Lecture 13 CS110 all 016 Parse trees: text, section 3.36 Definition of Java Language, sometimes useful: docs.oracle.com/javase/specs/jls/se8/html/index.html

More information

Prolog. Prolog: Programmation en Logique R.A. Kowalski: Predicate logic as a programming language, Proc IFIP 1974, pp.

Prolog. Prolog: Programmation en Logique R.A. Kowalski: Predicate logic as a programming language, Proc IFIP 1974, pp. Prolog Prolog: Programmation en Logique 1974 - R.A. Kowalski: Predicate logic as a programming language, Proc IFIP 1974, pp. 569-574: First-order predicate logic for the specification of data and relationships

More information

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology Trees : Part Section. () (2) Preorder, Postorder and Levelorder Traversals Definition: A tree is a connected graph with no cycles Consequences: Between any two vertices, there is exactly one unique path

More information

CSC384: Intro to Artificial Intelligence Prolog Tutorials 3&4. Hojjat Ghaderi, Fall 2006, University of Toronto

CSC384: Intro to Artificial Intelligence Prolog Tutorials 3&4. Hojjat Ghaderi, Fall 2006, University of Toronto CSC384: Intro to Artificial Intelligence Prolog Tutorials 3&4 1 Debugging Programs in Prolog We talked about the graphical debugger under Windows. Now, the text-based debugger: You can put a breakpoint

More information

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures. Trees Q: Why study trees? : Many advance DTs are implemented using tree-based data structures. Recursive Definition of (Rooted) Tree: Let T be a set with n 0 elements. (i) If n = 0, T is an empty tree,

More information

Question 7.11 Show how heapsort processes the input:

Question 7.11 Show how heapsort processes the input: Question 7.11 Show how heapsort processes the input: 142, 543, 123, 65, 453, 879, 572, 434, 111, 242, 811, 102. Solution. Step 1 Build the heap. 1.1 Place all the data into a complete binary tree in the

More information

7.Deep lists. A trivial case of a deep list is a simple (or shallow) list. Examples of deep lists include:

7.Deep lists. A trivial case of a deep list is a simple (or shallow) list. Examples of deep lists include: 7.Deep lists The deep list type in prolog represents a recursive structure, where several lists of variable depth are nested one in another. Formally a deep list can be defined by: A trivial case of a

More information

Trees. (Trees) Data Structures and Programming Spring / 28

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

CMPT 225. Binary Search Trees

CMPT 225. Binary Search Trees CMPT 225 Binary Search Trees Trees A set of nodes with a single starting point called the root Each node is connected by an edge to some other node A tree is a connected graph There is a path to every

More information

ADTS, GRAMMARS, PARSING, TREE TRAVERSALS

ADTS, GRAMMARS, PARSING, TREE TRAVERSALS 1 Prelim 1 2 Where: Kennedy Auditorium When: A-Lib: 5:30-7 Lie-Z: 7:30-9 (unless we explicitly notified you otherwise) ADS, GRAMMARS, PARSING, R RAVRSALS Lecture 13 CS2110 Spring 2016 Pointers to material

More information

F453 Module 7: Programming Techniques. 7.2: Methods for defining syntax

F453 Module 7: Programming Techniques. 7.2: Methods for defining syntax 7.2: Methods for defining syntax 2 What this module is about In this module we discuss: explain how functions, procedures and their related variables may be used to develop a program in a structured way,

More information

Chapter 20: Binary Trees

Chapter 20: Binary Trees Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other

More information

Outline. Limitations of regular languages Parser overview Context-free grammars (CFG s) Derivations Syntax-Directed Translation

Outline. Limitations of regular languages Parser overview Context-free grammars (CFG s) Derivations Syntax-Directed Translation Outline Introduction to Parsing Lecture 8 Adapted from slides by G. Necula and R. Bodik Limitations of regular languages Parser overview Context-free grammars (CG s) Derivations Syntax-Directed ranslation

More information

CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g))

CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g)) CS61A Notes 02b Fake Plastic Trees Box and Pointer Diagrams QUESTIONS: Evaluate the following, and draw a box-and-pointer diagram for each. (Hint: It may be easier to draw the box-and-pointer diagram first.)

More information

Data Structures - Binary Trees and Operations on Binary Trees

Data Structures - Binary Trees and Operations on Binary Trees ata Structures - inary Trees and Operations on inary Trees MS 275 anko drovic (UI) MS 275 October 15, 2018 1 / 25 inary Trees binary tree is a finite set of elements. It can be empty partitioned into three

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 13, 2017 Outline Outline 1 C++ Supplement.1: Trees Outline C++ Supplement.1: Trees 1 C++ Supplement.1: Trees Uses

More information

CS 280 Problem Set 10 Solutions Due May 3, Part A

CS 280 Problem Set 10 Solutions Due May 3, Part A CS 280 Problem Set 10 Due May 3, 2002 Part A (1) You are given a directed graph G with 1000 vertices. There is one weakly connected component of size 800 and several other weakly connected components of

More information

CSCI2100B Data Structures Trees

CSCI2100B Data Structures Trees CSCI2100B Data Structures Trees Irwin King king@cse.cuhk.edu.hk http://www.cse.cuhk.edu.hk/~king Department of Computer Science & Engineering The Chinese University of Hong Kong Introduction General Tree

More information

Friday, March 30. Last time we were talking about traversal of a rooted ordered tree, having defined preorder traversal. We will continue from there.

Friday, March 30. Last time we were talking about traversal of a rooted ordered tree, having defined preorder traversal. We will continue from there. Friday, March 30 Last time we were talking about traversal of a rooted ordered tree, having defined preorder traversal. We will continue from there. Postorder traversal (recursive definition) If T consists

More information

4. Suffix Trees and Arrays

4. Suffix Trees and Arrays 4. Suffix Trees and Arrays Let T = T [0..n) be the text. For i [0..n], let T i denote the suffix T [i..n). Furthermore, for any subset C [0..n], we write T C = {T i i C}. In particular, T [0..n] is the

More information

Concepts of programming languages

Concepts of programming languages Concepts of programming languages Prolog Winand, Roald, Sjoerd, Alexey and Anvar 1 What is logic programming? Logic programming is a type of programming paradigm which is largely based on formal logic.

More information

Modelica Change Proposal MCP-0019 Flattening (In Development) Proposed Changes to the Modelica Language Specification Version 3.

Modelica Change Proposal MCP-0019 Flattening (In Development) Proposed Changes to the Modelica Language Specification Version 3. Modelica Change Proposal MCP-0019 Flattening (In Development) Proposed Changes to the Modelica Language Specification Version 3.3 Revision 1 Table of Contents Preface 3 Chapter 1 Introduction 3 Chapter

More information

ChAmElEoN Parse Tree

ChAmElEoN Parse Tree ChAmElEoN Parse Tree Jack L. Watkin May 9, 2017 The objective of this appendix is to describe the abstract syntax tree (ast) generated by the ChAmElEoN parser. 1 Tree Node The ChAmElEoNparser builds an

More information

syntax tree - * * * - * * * * * 2 1 * * 2 * (2 * 1) - (1 + 0)

syntax tree - * * * - * * * * * 2 1 * * 2 * (2 * 1) - (1 + 0) 0//7 xpression rees rom last time: we can draw a syntax tree for the Java expression ( 0). 0 ASS, GRAMMARS, PARSING, R RAVRSALS Lecture 3 CS0 all 07 Preorder, Postorder, and Inorder Preorder, Postorder,

More information

10 Recursive Programming in Prolog

10 Recursive Programming in Prolog 10 Recursive Programming in Prolog What's in This Set of Notes? Examples Transforming Recursion to Iteration Recursive Comparison Joining Structures Accumulators Mapping Problems 10.1 Examples select_first(x,xs,ys)

More information

AstLog. Outline. Microsoft Research.

AstLog. Outline. Microsoft Research. AstLog Microsoft Research. Outline Where does it come from? Prolog, with examples. Basic concepts of ASTLog. Simple examples in ASTLog. More complex examples. Why is this (apparently) not very widely used?

More information

Introduction to Functional Programming

Introduction to Functional Programming Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 19, 2016 Outline Outline 1 Chapter 7: Trees Outline Chapter 7: Trees 1 Chapter 7: Trees Uses Of Trees Chapter 7: Trees

More information

Assignment 1. Stefano Guerra. October 11, The following observation follows directly from the definition of in order and pre order traversal:

Assignment 1. Stefano Guerra. October 11, The following observation follows directly from the definition of in order and pre order traversal: Assignment 1 Stefano Guerra October 11, 2016 1 Problem 1 Describe a recursive algorithm to reconstruct an arbitrary binary tree, given its preorder and inorder node sequences as input. First, recall that

More information

Trees and Tree Traversals. Binary Trees. COMP 210: Object-Oriented Programming Lecture Notes 8. Based on notes by Logan Mayfield

Trees and Tree Traversals. Binary Trees. COMP 210: Object-Oriented Programming Lecture Notes 8. Based on notes by Logan Mayfield OMP 210: Object-Oriented Programming Lecture Notes 8 Trees and Tree Traversals ased on notes by Logan Mayfield In these notes we look at inary Trees and how to traverse them. inary Trees Imagine a list.

More information

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents Section 5.5 Binary Tree A binary tree is a rooted tree in which each vertex has at most two children and each child is designated as being a left child or a right child. Thus, in a binary tree, each vertex

More information

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion simple and/or composition of goals hides complex control patterns not easily represented by traditional

More information

Math 15 - Spring Homework 5.2 Solutions

Math 15 - Spring Homework 5.2 Solutions Math 15 - Spring 2017 - Homework 5.2 Solutions 1. (5.2 # 14 (not assigned)) Use Prim s algorithm to construct a minimal spanning tree for the following network. Draw the minimal tree and compute its total

More information

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge Trees & Heaps Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Fall 2018 Jill Seaman!1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every

More information

Outline. Parser overview Context-free grammars (CFG s) Derivations Syntax-Directed Translation

Outline. Parser overview Context-free grammars (CFG s) Derivations Syntax-Directed Translation Outline Introduction to Parsing (adapted from CS 164 at Berkeley) Parser overview Context-free grammars (CFG s) Derivations Syntax-Directed ranslation he Functionality of the Parser Input: sequence of

More information

XSB. Tim Finin University of Maryland Baltimore County. What XSB offers Tabling Higher order logic programming. Negation. sort of.

XSB. Tim Finin University of Maryland Baltimore County. What XSB offers Tabling Higher order logic programming. Negation. sort of. XSB Tim Finin University of Maryland Baltimore County 2/19/02 1 Overview What XSB offers Tabling Higher order logic programming sort of Negation an Honors University in Maryland 2 What XSB Offers LP languages

More information

Coalgebraic Semantics in Logic Programming

Coalgebraic Semantics in Logic Programming Coalgebraic Semantics in Logic Programming Katya Komendantskaya School of Computing, University of Dundee, UK CSL 11, 13 September 2011 Katya (Dundee) Coalgebraic Semantics in Logic Programming TYPES 11

More information

March 20/2003 Jayakanth Srinivasan,

March 20/2003 Jayakanth Srinivasan, Definition : A simple graph G = (V, E) consists of V, a nonempty set of vertices, and E, a set of unordered pairs of distinct elements of V called edges. Definition : In a multigraph G = (V, E) two or

More information

CSC148 Week 6. Larry Zhang

CSC148 Week 6. Larry Zhang CSC148 Week 6 Larry Zhang 1 Announcements Test 1 coverage: trees (topic of today and Wednesday) are not covered Assignment 1 slides posted on the course website. 2 Data Structures 3 Data Structures A data

More information

Tests, Backtracking, and Recursion

Tests, Backtracking, and Recursion Tests, Backtracking, and Recursion Artificial Intelligence Programming in Prolog Lecture 3 30/09/04 30/09/04 AIPP Lecture 3: Rules, Results, and Backtracking 1 Re-cap A Prolog program consists of predicate

More information

Simple Facts. Eisenhower. Fillmore. Delano. Grover. Abraham. Clinton. Herbert. Barack

Simple Facts. Eisenhower. Fillmore. Delano. Grover. Abraham. Clinton. Herbert. Barack Logic Programming Announcements The Logic Language The Logic Language The Logic language was invented for Structure and Interpretation of Computer Programs Based on Prolog (1972) Expressions are facts

More information

EE 368. Weeks 5 (Notes)

EE 368. Weeks 5 (Notes) EE 368 Weeks 5 (Notes) 1 Chapter 5: Trees Skip pages 273-281, Section 5.6 - If A is the root of a tree and B is the root of a subtree of that tree, then A is B s parent (or father or mother) and B is A

More information

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false. Name: Class: Date: CSCI-401 Examlet #5 True/False Indicate whether the sentence or statement is true or false. 1. The root node of the standard binary tree can be drawn anywhere in the tree diagram. 2.

More information

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking Review for Test 2 (Chapter 6-10) Chapter 6: Template functions & classes 1) What is the primary purpose of template functions? A. To allow a single function to be used with varying types of arguments B.

More information

COSC 2011 Section N. Trees: Terminology and Basic Properties

COSC 2011 Section N. Trees: Terminology and Basic Properties COSC 2011 Tuesday, March 27 2001 Overview Trees and Binary Trees Quick review of definitions and examples Tree Algorithms Depth, Height Tree and Binary Tree Traversals Preorder, postorder, inorder Binary

More information

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University U Kang (2016) 1 In This Lecture The concept of binary tree, its terms, and its operations Full binary tree theorem Idea

More information

Implementação de Linguagens 2016/2017

Implementação de Linguagens 2016/2017 Implementação de Linguagens Ricardo Rocha DCC-FCUP, Universidade do Porto ricroc @ dcc.fc.up.pt Ricardo Rocha DCC-FCUP 1 Logic Programming Logic programming languages, together with functional programming

More information

Database Theory VU , SS Introduction to Datalog. Reinhard Pichler. Institute of Logic and Computation DBAI Group TU Wien

Database Theory VU , SS Introduction to Datalog. Reinhard Pichler. Institute of Logic and Computation DBAI Group TU Wien Database Theory Database Theory VU 181.140, SS 2018 2. Introduction to Datalog Reinhard Pichler Institute of Logic and Computation DBAI Group TU Wien 13 March, 2018 Pichler 13 March, 2018 Page 1 Database

More information

CMPS 277 Principles of Database Systems. https://courses.soe.ucsc.edu/courses/cmps277/fall11/01. Lecture #11

CMPS 277 Principles of Database Systems. https://courses.soe.ucsc.edu/courses/cmps277/fall11/01. Lecture #11 CMPS 277 Principles of Database Systems https://courses.soe.ucsc.edu/courses/cmps277/fall11/01 Lecture #11 1 Limitations of Relational Algebra & Relational Calculus Outline: Relational Algebra and Relational

More information

Index-assisted approximate matching

Index-assisted approximate matching Index-assisted approximate matching Ben Langmead Department of Computer Science You are free to use these slides. If you do, please sign the guestbook (www.langmead-lab.org/teaching-materials), or email

More information

Binary Trees

Binary Trees Binary Trees 4-7-2005 Opening Discussion What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment? What is a Tree? You are all familiar with what

More information

Prolog. Logic Programming vs Prolog

Prolog. Logic Programming vs Prolog Language constructs Prolog Facts, rules, queries through examples Horn clauses Goal-oriented semantics Procedural semantics How computation is performed? Comparison to logic programming 1 Logic Programming

More information

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1 Trees Introduction & Terminology Cinda Heeren / Geoffrey Tien 1 Review: linked lists Linked lists are constructed out of nodes, consisting of a data element a pointer to another node Lists are constructed

More information

Prolog-2 nd Lecture. Prolog Predicate - Box Model

Prolog-2 nd Lecture. Prolog Predicate - Box Model Prolog-2 nd Lecture Tracing in Prolog Procedural interpretation of execution Box model of Prolog predicate rule How to follow a Prolog trace? Trees in Prolog use nested terms Unification Informally Formal

More information

Trees: examples (Family trees)

Trees: examples (Family trees) Ch 4: Trees it s a jungle out there... I think that I will never see a linked list useful as a tree; Linked lists are used by everybody, but it takes real smarts to do a tree Trees: examples (Family trees)

More information

Trees. CSE 373 Data Structures

Trees. CSE 373 Data Structures Trees CSE 373 Data Structures Readings Reading Chapter 7 Trees 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical relationships File directories

More information

COMP219: Artificial Intelligence. Lecture 6: Recursion in Prolog

COMP219: Artificial Intelligence. Lecture 6: Recursion in Prolog COMP219: Artificial Intelligence Lecture 6: Recursion in Prolog 1 Overview Last time Introduction to Prolog: facts, rules, queries; family tree program Today: Recursive rules in Prolog; writing and evaluating

More information

Syntactic Analysis. Top-Down Parsing. Parsing Techniques. Top-Down Parsing. Remember the Expression Grammar? Example. Example

Syntactic Analysis. Top-Down Parsing. Parsing Techniques. Top-Down Parsing. Remember the Expression Grammar? Example. Example Syntactic Analysis op-down Parsing Parsing echniques op-down Parsers (LL(1), recursive descent) Start at the root of the parse tree and grow toward leaves Pick a production & try to match the input Bad

More information

Trees. Tree Structure Binary Tree Tree Traversals

Trees. Tree Structure Binary Tree Tree Traversals Trees Tree Structure Binary Tree Tree Traversals The Tree Structure Consists of nodes and edges that organize data in a hierarchical fashion. nodes store the data elements. edges connect the nodes. The

More information

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w Chapter 7 Trees 7.1 Introduction A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w Tree Terminology Parent Ancestor Child Descendant Siblings

More information

Semantic actions for expressions

Semantic actions for expressions Semantic actions for expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate representations

More information

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am. The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

More information

Let s Get Functional. Learn You Some Erlang for Great Good! 2013, Fred Hébert

Let s Get Functional. Learn You Some Erlang for Great Good! 2013, Fred Hébert 6 Higher-Order Functions An important part of all functional programming languages is the ability to take a function you defined and then pass it as a parameter to another function. This binds that function

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2008S-19 B-Trees David Galles Department of Computer Science University of San Francisco 19-0: Indexing Operations: Add an element Remove an element Find an element,

More information

List of Practical for Master in Computer Application (5 Year Integrated) (Through Distance Education)

List of Practical for Master in Computer Application (5 Year Integrated) (Through Distance Education) List of Practical for Master in Computer Application (5 Year Integrated) (Through Distance Education) Directorate of Distance Education Guru Jambeshwar University of Science & Technology, Hissar First

More information

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text) Lec 17 April 8 Topics: binary Trees expression trees Binary Search Trees (Chapter 5 of text) Trees Linear access time of linked lists is prohibitive Heap can t support search in O(log N) time. (takes O(N)

More information

Friday Four Square! 4:15PM, Outside Gates

Friday Four Square! 4:15PM, Outside Gates Binary Search Trees Friday Four Square! 4:15PM, Outside Gates Implementing Set On Monday and Wednesday, we saw how to implement the Map and Lexicon, respectively. Let's now turn our attention to the Set.

More information

Neo4J: Graph Database

Neo4J: Graph Database February 24, 2013 Basics is a data storage and query system designed for storing graphs. Data as a series of relationships, modelled as a directed graph. Recall, a graph is a pair of sets: G(V, E) vertices

More information

Topic B: Backtracking and Lists

Topic B: Backtracking and Lists Topic B: Backtracking and Lists 1 Recommended Exercises and Readings From Programming in Prolog (5 th Ed.) Readings: Chapter 3 2 Searching for the Answer In order for a Prolog program to report the correct

More information

Week 7 Prolog overview

Week 7 Prolog overview Week 7 Prolog overview A language designed for A.I. Logic programming paradigm Programmer specifies relationships among possible data values. User poses queries. What data value(s) will make this predicate

More information

Arithmetic Terms are Symbolic

Arithmetic Terms are Symbolic Arithmetic Terms are Symbolic Evaluation of an arithmetic term into a numeric value must be forced. That is, 1+2 is an infix representation of the relation +(1,2). This term is not an integer! Therefore?-

More information

CMSC 341 Lecture 10 Binary Search Trees

CMSC 341 Lecture 10 Binary Search Trees CMSC 341 Lecture 10 Binary Search Trees John Park Based on slides from previous iterations of this course Review: Tree Traversals 2 Traversal Preorder, Inorder, Postorder H X M A K B E N Y L G W UMBC CMSC

More information

Why Do We Need Trees?

Why Do We Need Trees? CSE 373 Lecture 6: Trees Today s agenda: Trees: Definition and terminology Traversing trees Binary search trees Inserting into and deleting from trees Covered in Chapter 4 of the text Why Do We Need Trees?

More information

Week 9 Student Responsibilities. Mat Example: Minimal Spanning Tree. 3.3 Spanning Trees. Prim s Minimal Spanning Tree.

Week 9 Student Responsibilities. Mat Example: Minimal Spanning Tree. 3.3 Spanning Trees. Prim s Minimal Spanning Tree. Week 9 Student Responsibilities Reading: hapter 3.3 3. (Tucker),..5 (Rosen) Mat 3770 Spring 01 Homework Due date Tucker Rosen 3/1 3..3 3/1 DS & S Worksheets 3/6 3.3.,.5 3/8 Heapify worksheet ttendance

More information

Lecture 6: More Lists

Lecture 6: More Lists Lecture 6: More Lists Theory Define append/3, a predicate for concatenating two lists, and illustrate what can be done with it Discuss two ways of reversing a list A naïve way using append/3 A more efficient

More information

Quick n Dirty Prolog Tutorial

Quick n Dirty Prolog Tutorial CSc 245 Introduction to Discrete Structures Quick n Dirty Prolog Tutorial (McCann) Last Revised: February 2014 Background: Prolog, whose name is from the phrase PROgramming in LOGic, is a special purpose

More information

Logic programming I. Henrik Boström Stockholm University. Facts Queries Rules Terms Recursion Lists Negation

Logic programming I. Henrik Boström Stockholm University. Facts Queries Rules Terms Recursion Lists Negation Logic programming I Henrik Boström Stockholm University Facts Queries Rules Terms Recursion Lists Negation Logic programs A logic program consists of facts and rules. A logic program is executed by responding

More information

CSE 203A: Randomized Algorithms

CSE 203A: Randomized Algorithms CSE 203A: Randomized Algorithms (00:30) The Minimax Principle (Ch 2) Lecture on 10/18/2017 by Daniel Kane Notes by Peter Greer-Berezovsky Game Tree Evaluation (2.1) - n round deterministic 2-player game

More information

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?

More information

Lab Exercise 8 Binary Search Trees

Lab Exercise 8 Binary Search Trees Lab Exercise 8 Binary Search Trees A binary search tree is a binary tree of ordered nodes. The nodes are ordered by some key value, for example: alphabetic or numeric. The left subtree of every node (if

More information

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion simple and/or composition of goals hides complex control patterns not easily represented by traditional

More information