Review: computing list results Many programs require list results to be computed, built and returned Many programs require list results to be computed,

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Prolog Programming (Volume 5) Dr W.F. Clocksin. List cells + Unification = Great Idea Normally we use ‘proper lists’, which are defined according to the.
11/10/04 AIPP Lecture 6: Built-in Predicates1 Combining Lists & Built-in Predicates Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/8.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
”assert” and ”retract”
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
Chapter 12 - Logic Programming
Recursion CSC 220: Data Structure Winter Introduction A programming technique in which a function calls itself. One of the most effective techniques.
Chapter 4: Trees Radix Search Trees Lydia Sinapova, Simpson College Mark Allen Weiss: Data Structures and Algorithm Analysis in Java.
Blind Search-Part 2 Ref: Chapter 2. Search Trees The search for a solution can be described by a tree - each node represents one state. The path from.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Prolog Ross (Tate). Filling in the Blanks Rather than reverse((a,b)) returns (b,a) Rather than reverse((a,b)) returns (b,a) What X makes reverse((a,b),
Data Structures, Lists, and Trees CS-2301 B-term Data Structures — Lists and Trees CS-2301, System Programming for Non-majors (Slides include materials.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 20: Binary Trees.
Data Structures — Lists and Trees CS-2301, B-Term Data Structures — Lists and Trees CS-2301, System Programming for Non-Majors (Slides include materials.
Binary Trees Chapter 6.
CS261 Data Structures DFS and BFS – Edge List Representation.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
CHAPTER 71 TREE. Binary Tree A binary tree T is a finite set of one or more nodes such that: (a) T is empty or (b) There is a specially designated node.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Chapter Tow Search Trees BY HUSSEIN SALIM QASIM WESAM HRBI FADHEEL CS 6310 ADVANCE DATA STRUCTURE AND ALGORITHM DR. ELISE DE DONCKER 1.
Digital Electronics Data Structures LISP
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
1 Data Structures Lists and Trees. 2 Real-Life Computational Problems All about organizing data! –What shape the data should have to solve your problem.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
1 CO Games Development 1 Week 6 Introduction To Pathfinding + Crash and Turn + Breadth-first Search Gareth Bellaby.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Data Structures and Algorithms Stacks. Stacks are a special form of collection with LIFO semantics Two methods int push( Stack s, void *item ); - add.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Chapter 6 Binary Trees. 6.1 Trees, Binary Trees, and Binary Search Trees Linked lists usually are more flexible than arrays, but it is difficult to use.
30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists1 Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim.
15/11/04 AIPP Lecture 14: Database Manipulation1 Database Manipulation Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 14 15/11/04.
Symbol Tables and Search Trees CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
1 Searching Searching in a sorted linked list takes linear time in the worst and average case. Searching in a sorted array takes logarithmic time in the.
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.
Basic Problem Solving Search strategy  Problem can be solved by searching for a solution. An attempt is to transform initial state of a problem into some.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Code Generation CPSC 388 Ellen Walker Hiram College.
1 i206: Lecture 12: Hash Tables (Dictionaries); Intro to Recursion Marti Hearst Spring 2012.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
CHAPTER 51 LINKED LISTS. Introduction link list is a linear array collection of data elements called nodes, where the linear order is given by means of.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
Data Structures and Algorithms Lists, Stacks, Queues, and Graphs Sorting and searching algorithms.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Mohammed I DAABO COURSE CODE: CSC 355 COURSE TITLE: Data Structures.
Representing Structure and Behavior
Chapter 12 – Data Structures
Sorted Linked List Same objective as a linked list, but it should be sorted Sorting can be custom according to the type of nodes Offers speedups over non-sorted.
Data Structure Interview Question and Answers
12 C Data Structures.
CS 1114: Implementing Search
Data Structures Interview / VIVA Questions and Answers
Introduction to Data Structure
Tests, Backtracking, and Recursion
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Arrays and Linked Lists
ITEC 2620M Introduction to Data Structures
Lectures on Graph Algorithms: searching, testing and sorting
Chapter 12 :: Logic Languages
Data Structures & Algorithms
Symbol Table 薛智文 (textbook ch#2.7 and 6.5) 薛智文 96 Spring.
Recurrences.
Prolog Based on: Chapter 12 of PLP “Seven languages in seven weeks”
Presentation transcript:

Review: computing list results Many programs require list results to be computed, built and returned Many programs require list results to be computed, built and returned Ways to build lists... Ways to build lists... (1) append intermediate answer to an overall result list (1) append intermediate answer to an overall result list make_intlist(M, N, [ ]) :- M > N. make_intlist(M, N, L) :- M =< N, M2 is M + 1, make_intlist(M2, N, L2), append([M], L2, L). L2 is intermediate answer must pass L back to get final answer in calling predicate 1COSC 2P93 Prolog: Lists_DS

Building lists (2) prepend intermediate solution in predicate head make_intlist(M, N, [ ]) :- M > N. make_intlist(M, N, [M|L2]) :- M =< N, M2 is M + 1, make_intlist(M2, N, L2). L2 is intermediate answer concatenate M to start of L2 2COSC 2P93 Prolog: Lists_DS

Building lists (3) create a new argument with intermediate list; return it back when recursion has terminated ?- make_intlist(N, [ ], L). make_intlist(N, L, L) :- N < 0. make_intlist(N, L2, L) :- N >= 0, N2 is N - 1, % runs down from N to 0 make_intlist(N2, [N | L2], L). L2 starts as empty list; successive N’s are added to it (must count downward, or they’ll be in inverse order!) when N is negative, then return this intermediate built list, which is soln L will be a variable term UNTIL first clause activates, at which time final solution passed all the way to top 3COSC 2P93 Prolog: Lists_DS

A common technique... Here is a common Prolog programming technique, where the final result is unified when the recursion terminates... my_predicate(... vars..., Final, Final) :- % terminate recursion my_predicate(... vars..., Intermed, Final) :- % recursive case(s), my_predicate(...vars..., Intermed2, Final). 4COSC 2P93 Prolog: Lists_DS

A common list building error Building up list during calls, but not returning as final result: make_intlist(N, L) :- N < 0. make_intlist(N, L) :- N >= 0, N2 is N - 1, % runs from N down to 0 make_intlist(N2, [N | L]). Problem: the term “[N | L]” in the recursive call builds up an answer however, looking at the head of the rule, only L is available to the calling routine --> the computed “N” result is not passed back! 5COSC 2P93 Prolog: Lists_DS

Prolog’s symbolic denotation of data means that complex data structures are easily derived 1. database records: invent a convention for representing data eg. define a structure ‘rec’ with 6 args, each argument = DB field first arg is key other args are interpreted according to their position in record, so programs must know this conventional structure rec(acct(Acct),name(First,MI,Last), bdate(day(D),mo(M),year(Y)), sin(SIN,) addr(Street,City,Prov), bal(Balance)) rec acct name bdate sin addr bal day mo year Other data structures 6COSC 2P93 Prolog: Lists_DS

Records There are a number of ways of storing a database with this information (a) List: [ Rec1, Rec2, Rec3,...., RecK ] add_rec(Rec, OldDB, [Rec|OldDB]) :- get_key(Rec, Key), \+ member(rec(Key,_,_,_,_), OldDB). get_rec(Key, DB, rec(Key,A,B,C,D,E) :- member(rec(Key,A,B,C,D,E), DB). del_rec(Key,DB, NewDB) :- delete(rec(acct(Key),_,_,_,_,_), DB, NewDB). get_key(rec(Key,_,_,_,_,_), Key). delete(X,[X|R], R). delete(X, [Y|R], [Y|R2]) :- delete(X, R, R2). 7COSC 2P93 Prolog: Lists_DS

Records (b) another approach is to label each field, and place fields in a list structure themselves [name(F,MI,L), acct(Acct), sin(SIN), address(S,C,P),... ] Database: [ [rec1], [rec2],..., [recK] ] (ie. a list of lists) advantage: 1. fields can be in any order 2. easy to modify records: just add another labelled element disadvantage: To find a field, must search the record list get_key(Rec, Key) :- member(acct(Key), Rec). % searches rec list for Key get_rec(Key, DB, Rec) :- member(Rec, DB), % backtracking selects each element of list DB get_key(Key, Rec). % does this record match? 8

Records (c) another way to represent them - as Prolog facts! rec(acct(38349), name(john,j,smith),....). or rec([acct(38349), sin( ), name(john,j,smith),... ] ). We will discuss how to add or delete such records later hint: use Prolog’s builtin “assert” and “retract” predicates (Prolog also has efficient means for accessing such records) 9COSC 2P93 Prolog: Lists_DS

Data Structures: stacks Stack: use the list % push(Item, Stac, NewStack) succeeds if, by pushing Item % on Stack, we get NewStack push(Item, Stack, [Item | Stack]). % pop(Item, Stack, NewStack) succeeds if Item is popped from % Stack, resulting in NewStack pop(Item, [Item| Rest], Rest). % top and is_empty are self-explanatory... top(Top, [Top | _]). is_empty( [ ] ). Note that most programs don’t use these. Instead, stacks are implemented directly as lists in arguments 10COSC 2P93 Prolog: Lists_DS

Data Structures: Sorted Binary tree Binary tree list is too inefficient for large databases; if database has K records, a get or delete requires an average of K/2 comparisons during list search binary trees permit DB to be kept in order all the time two types of nodes: nil : empty branch/tree tree(Left_branch, Key, Right_branch) : tree node with data eg. tree(tree(nil,2,nil), 4, tree(tree(nil,5,nil), 6, nil)) represents: COSC 2P93 Prolog: Lists_DS

Binary trees binary trees are very useful when they are sorted: keys on the left branch are less than the node, and keys on right are greater % add_bintree(Key, OldTree, NewTree)... add_bintree(Key, nil, tree(nil, Key, nil). add_bintree(Key, tree(L, Key, R), tree(L, Key, R)). add_bintree(Key, tree(L, K, R), tree(L2, K,R)) :- Key < K, add_bintree(Key, L, L2). add_bintree(Key, tree(L, K, R), tree(L, K, R2) :- Key > K, add_bintree(Key, R, R2). 12COSC 2P93 Prolog: Lists_DS

Data Structures: graphs (a) Representing directed graphs as program clauses edge(d, c).edge(f, e).edge(h, l). edge(b, c).edge(f, i).edge(l, k). edge(b, f).edge(i, j).edge(g, f). edge(a, b).edge(j, k).edge(g, h). edge(k, g).edge(a, f). a b c d f e g h l k j i 13COSC 2P93 Prolog: Lists_DS

Graphs Can then search for connections within the graph: path(A, B) :- edge(A,B). path(A,B) :- edge(A,C), path(C,B). note similarity with ‘ancestor’ ancestor(A,B) :- parent(A,B). ancestor(A,B) :- parent(A,C), ancestor(C,B). However, unlike family relationships, graphs can have loops using Prolog’s backtracking, it can easily get sidetracked into a loop eg. ?- path(j,a) will go thru: j - k - g - f - i - j - etc 14COSC 2P93 Prolog: Lists_DS

Graphs (b) use a list [v(Node1, Nodelist1), v(Node2, Nodelist2),...] then graph([ v(a, [b, f]), v(b, [c,f]), v(d, [f]), v(f, [e,i]), v(g, [f,h]), v(i, [j]), v(j, [k]), v(k, [g]), v(l, [k]), v(h, [l]) ] ). Can write a ‘path’ routine which keeps track of places it has already been to; if it has been to a place already, then don’t go there again! (can also do this with the other representation) 15

Data Structures: graphs path(Start, Finish) :- graph(G), smart_path(Start, Finish, G, [ ]). smart_path(A, B, G, _) :- member(v(A,L), G), member(B, L). smart_path(A, B, G, Previous) :- member(v(A,L), G), member(C, L), \+ member(C, Previous), smart_path(C, B, G, [A | Previous]). 16COSC 2P93 Prolog: Lists_DS

Data structures Of course, structures permit arbitrarily complex data structures to be represented foo( List, cons1, Stack_of_bintrees, Bintree_of_stacks, etc...) The power of symbolic execution is that you can define these structures symbolically, without regards to implementation details (memory allocation, pointers,...) 17COSC 2P93 Prolog: Lists_DS