220 likes | 443 Views
Prolog. or: How I Learned to Stop Worrying and Love the Search. Hello. I’m Zach, one of Sorin’s students. ztatlock@cs.ucsd.edu. Search. Any cycles?. Search. How about now?. Search. And now?. Search. Reach from stopping by ?. Search is Fundamental.
E N D
Prolog or: How I Learned to Stop Worryingand Love the Search
Hello. I’m Zach, one of Sorin’s students. ztatlock@cs.ucsd.edu
Search Any cycles?
Search How about now?
Search And now?
Search Reach from stopping by ?
Search is Fundamental Natural way to phrase problems: Is there an X such that Y? Ubiquitous in Computer Science:
Prolog: Interface to Search Search is declarative say what you want not how to get it Often radical simplification shorter, clearer programs less development effort fewer bugs SEARCH
Prolog Anatomy 101 Prolog programs do three things: Declare Facts known points in the search space 2. Declare Rules add new points to search space based on old ones 3. Query over Search Space search for a point
Prolog Anatomy 101 Facts : known points Rules : add new points from old points Query: is reachable? Query Rules Facts
Prolog Basic Syntax Backtracking Search Examples in the toplevel: • Variables in Queries • Negation • Search Order
Basic Syntax Declare Facts: parent(homer, bart). parent(marge, bart). parent(mona, homer). Known points in search space Basis of all we can conclude
Basic Syntax Simple Query: ?- parent(homer, bart). true. ?- parent(mona, bart). false. Ask if a particular point is in search space
Basic Syntax Declare Rules: grandparent(GP, GC) :- parent(GP, P), parent(P, GC). ADD THIS NEW POINT IF YOU FIND THESE OLD POINTS VARIABLES
Atoms vs. Variables Atom starts with lowercase letter particular individual object only equal to self Variable starts with uppercase letter “hole” replaceable by atom
Basic Syntax grandparent(GP, GC) :- parent(GP, P), parent(P, GC). grandparent(GP, GC) can be added to search space If you find 3 atoms GP,P,GC Such that both parent(GP, P) andparent(P, GC)
Basic Syntax Query that requires Rule: ?- grandparent(mona, bart). true. ?- grandparent(homer, bart). false. Q: Which query takes longer?
Prolog Basic Syntax Backtracking Search Examples in the toplevel: • Variables in Queries • Negation • Search Order
Backtracking Search Query : is in search space? Prolog searches for backward: Start at Look for path back to Facts using Rules Top-down approach since Bottom-up is too inefficient
Backtracking Search Search( ) 1. in search space? Success! 2. For each rule R that could add : For each old node R requires : If Search( ) fails, try next rule. All old nodes found. Success! 3. Not in space, no rule can add. Fail.
Prolog Basic Syntax Backtracking Search Examples in the toplevel: • Variables in Queries • Negation • Search Order