% CSE 130: Spring 2012
% Logic Programming
% Ranjit Jhala, UC San Diego 


## News

- PA 7 is out, due Fri 6/8

### PA5, 6 Issues

- Bear with us, but let us know of anomalies

### Final

- Tuesday **6/12/2012** from **7-10pm**

- CENTER 105

- Stay tuned for **review session**

## Logic Programming

### Traditional Languages

> - **Program** = **Algorithm** + **Data Structures**

> - **Execute**

### Prolog 

> - **Program** = **Facts** + **Rules**

> - **Queried**

## Logic Programming

- <img src="../static/spock_logic.jpg" width=600 align="middle"/> 

 
## Prolog History

> - 1970s: Logic + Automated Theorem Proving

> - Developed for **Artificial Intelligence** 

## Prolog : Original Vision "Expert Systems"

### Collection of Facts

> - *Carnitas is Mexican*

### Collection of Rules

> - *Mexican food is delicious*

### Queries

> - *What is a delicious food ?*

### Deductions 

> - *Carnitas!* 

# You don't RUN a Prolog Program, you ASK it QUESTIONS

## Declarative Programming

> - Specify **what** you want 

> - Specify **desired properties** of result

> - Not **how** to obtain result 


# Declarative Programming: Ideal for Searching Large Space of Results

## Declarative Programming

Ideal for Searching Large Space of Results

### Philosophy 

> - It is often **hard**  to specify **search** algorithm 

> - But **easy** to specify the characteristics of the solution.

# Declarative Programming: Super Mainstream Example ???

## Declarative Programming: Application Orbitz/Expedia/etc.

### Collection of Facts

- Airports
- Flights
- Times
- Durations
- Costs

### Collection of Rules

**If** 

- travel from `A` to `B` with price (`P1`), duration ...
- travel from `B` to `C` with price (`P2`), duration ...

**Then** 

- travel from `A` to `C` with price (`P1 + P2`), duration ...

### Queries

> - What is cheapest flight from SAN to JFK with duration < 6 Hrs ?

## Declarative Programming: "Operations Research"

Specifically **Linear Programming** (CSE 101)

### Collection of Facts

> - **El Cuervo** makes two products
>     - CA Burrito (profit = `$2`)
>     - Fish Taco  (profit = `$1`)

### Collection of Rules

> - Burrito Capacity < `200` 
> - Taco Capacity    < `500` 
> - Total Capacity   < `400`

### Queries

> - How many burritos and tacos to **maximize** profit?

~~~~~{.scala}
max     2.x + 1.y       /* profit           */
s.t.    x   < 200       /* burrito capacity */
        y   < 400       /* taco    capacity */
        x+y < 300       /* total   capacity */
          0 < x, y      /* must produce!    */  
~~~~~

## Declarative Programming

Used heavily in many domains (together with statistical methods)

> - Scheduling 
>     - Travel, Sports, ...

> - Rule-based Anomaly detection 
>     - Credit card fraud!

> - SQL (and similar DB Query Languages)
>     - Find all pairs of stocks, with same price on same day,
>     - More than 50 times last year

> - Many of these are inspired-by / subsets of Prolog ...

# Prolog: New Way To Think About Programming ...

# Prolog: ... Programming As Proving!

## Plan 

### Language

> 1. Terms
> 2. Facts
> 3. Queries (Implementation: Unification)
> 4. Rules
> 5. Programs (Implementation: Backtracking Search)

### Programming

> - Numeric Computation
> - Data Structures
> - Puzzle Solving

## Language: Terms

Prolog Program

- **Facts** 
- **Rules**

... but facts and rules **about what** ?

> - Terms


## Terms are Prolog's way of representing Data

"Tree-like" values, similar to Ocaml ADTs

### Four Kinds of Terms

> 1. **Constants** 

> 2. **Atoms** 

> 3. **Variables**

> 4. **Compound Terms**

## Prolog Terms: Constants

**Constants** the simplest term, representing primitive values

> - Basic types like integers, reals

> - Examples: `1`, `92`, `4.4`  


## Prolog Terms: Atoms 

**Atom:** any identifier starting with **lower**-case

> - `x`, `alice`, `taco`, `giraffe`, `appleSauce`

## Prolog Terms: Atoms 

**Atom:** any identifier starting with **lower**-case

- `x`, `alice`, `taco`, `giraffe`, `appleSauce`

### Atoms are not variables

> - Elements of a single mega **enum** type
> - Similar to tags used in ML types (except ML tags are uppercase) 
>     - `type atoms = x | alice | taco | giraffe | appleSauce | ...`

## Prolog Terms: Atoms 

**Atom:** any identifier starting with **lower**-case

- `x`, `alice`, `taco`, `giraffe`, `appleSauce`

### Atoms are Uninterpreted Constants (Names)

> - Prolog knows **NOTHING** about the tags, they are just **names**

> - Each tag is **equal to** itself (more later...)
>     - `alice = alice`
>     - `taco = taco`

> - Each tag is **disequal to** every **other** tag
>     - `alice = taco` **never** holds in Prolog
>     - **never**
>     - **ever**

## Prolog Terms: Variables 

**Variables:** any identifier starting with **upper**-case 

- `X`, `Y`, `Z`, `Head`, `Tail`, `Taco`, `Burrito`, `Alice`, `Bob`

- `_` is the **wildcard** variable, similar to `ML`


### Variables are quite special ...

> - Even though `x = a` makes **no sense** to Prolog ...

> - ... `X = a` does have a meaning but **not** what you might think!


# Warning: Upper vs. Lowercase is common source of errors

## Prolog Terms: Compound Terms

**Compound** terms are of form `atom(term1, term2, term3, ...)`

Where each `term` is **one-of**

- constant
- atom
- variable
- compound term

## Prolog Terms: Compound Terms

**Compound** terms are of form `atom(term1, term2, term3, ...)`

Where each `term` is **one-of**

- constant
- atom
- variable
- compound term

### Examples

~~~~~{.prolog}
x(y, z)              % y, z       are atoms
parent(alice, bob)   % alice, bob are atoms
parent(alice, Child) % alice is an atom, Child is a variable
~~~~~


# Prolog Terms ARE NOT function calls

## Prolog Compound Terms 

> - Terms are NOT Function Calls!

> - More like **trees**

> - <img src="../static/prolog_tree1.png" width=400 align="middle"/> 

<!--
## Prolog Terms: Compound Terms 

**Compound** terms are of form `atom(term1, term2, term3, ...)`

Each `term` is **one-of**
- constant
- atom
- variable
- compound term

### Prolog Terms Generated By Grammar

~~~~~{.prolog}
const    := 0 | 1 | 2 | ...
    
atom     := [a-z][A-z,a-z,0-9]* | [0-9]* | ...
	
variable := [A-Z][a-z,A-Z,0-9]* | _ 

term     := const | atom | variable | atom(term,term,term,...)
~~~~~
-->

## Prolog Terms: Compound Terms 

**Compound** terms are of form `atom(term1, term2, term3, ...)`

Each `term` is **one-of**
- constant
- atom
- variable
- compound term

### An Ocaml Type For Prolog Terms

~~~~~{.ocaml}
type term = Constant of int
          | Atom     of string 
          | Variable of string 
	      | Compound of string * term list
~~~~~

## QUIZ: An Ocaml Type For Prolog Terms

~~~~~{.ocaml}
type term = Constant of int
          | Atom     of string 
          | Variable of string 
	      | Compound of string * term list
~~~~~

(Hint: **atom** = lowercase, **variable** = uppercase)

What Ocaml value of type `term` represents Prolog term `parent(alice, bob)` ?

**A.** `parent ("alice", "bob")`

**B.** `parent (Atom "alice", Atom "bob")`

**C.** `[Atom "parent"; Atom "alice"; Atom "bob"]`

**D.** `Compound ("parent", [Atom "alice"; Atom "bob"])`

**E.** `Compound (Atom "parent", [Atom "alice"; Atom "bob"])`

## Prolog Compound Terms

Prolog term `parent(alice, Charlie)` is represented by:

### Ocaml Value

~~~~~{.ocaml}
Compound (Atom "parent", [Atom "alice"; Var "Charlie"])
~~~~~

### Tree 

<img src="../static/prolog_tree2.png" width=300 align="middle"/> 

## QUIZ: An Ocaml Type For Prolog Terms

~~~~~{.ocaml}
type term = Constant of int
          | Atom     of string 
          | Variable of string 
	      | Compound of string * term list
~~~~~

(Hint: **atom** = lowercase, **variable** = uppercase)

What Ocaml value of type `term` represents Prolog term `factorial(5)` ?

**A.** `factorial(5)`

**B.** `factorial(Atom 5)`

**C.** `120` 

**D.** `Constant 120` 

**E.** `Compound ("factorial", [Constant 5])`


## Prolog Terms 

Prolog term `factorial(5)` is simply the tree  <img src="../static/prolog_tree3.png" width=200 align="middle"/> 

> - The term is just a box containing `5` labeled `factorial`

## Prolog Terms 

Prolog term `factorial(5)` is simply the tree  <img src="../static/prolog_tree3.png" width=200 align="middle"/> 

- The term is just a box containing `5` labeled `factorial`

### Function Symbols

> - `factorial` just a **label** called a **function symbol**

> - Prolog has **no idea** about **implementation** of function ...

<! -- > - Only thing prolog knows: `factorial(X) = factorial(X)`
-->

# Prolog Terms = (Tree) Structured Data 

## Plan 

### Language

1. Terms
2. **Facts**
3. Queries (Implementation: Unification)
4. Rules
5. Programs (Implementation: Backtracking Search)

### Programming

- Numeric Computation
- Data Structures
- Puzzle Solving

# Language: Facts

## Language: Facts

### Example

The following facts specify a list of **parent-child** relationships

~~~~~{.prolog}
parent(kim, holly).  
parent(margaret, kim).  
parent(herbert, margaret). 
parent(john, kim).
parent(felix, john).  
parent(albert, felix).
~~~~~

> - **Note** `kim`, `holly`, `margaret` etc. are all **atoms**

> - Facts are just terms (typically without variables.)

> - Specified by term followed by `.`


## Language: Facts

The following facts specify a list of **parent-child** relationships

~~~~~{.prolog}
parent(kim, holly).  
parent(margaret, kim).  
parent(herbert, margaret). 
parent(john, kim).
parent(felix, john).  
parent(albert, felix).
~~~~~

### Prolog maintains a Database of facts

> - You can make up and add new facts to the collection

> - We will be able to ask Prolog **queries** over these facts

# Predicates = Function Symbols Used For Facts

## Language: Facts

The following facts specify a list of **parent-child** relationships

~~~~~{.prolog}
parent(kim, holly).  
parent(margaret, kim).  
parent(herbert, margaret). 
parent(john, kim).
parent(felix, john).  
parent(albert, felix).
~~~~~

### Predicates = Function Symbols Used For Facts

> - Represent functions that evaluate to a boolean

> - e.g. `parent` is a predicate of **arity** 2 (that takes 2 arguments)

# Predicates Are Just Names: No Meaning Or Implementation

## Language: Facts

The following facts specify a list of **parent-child** relationships

~~~~~{.prolog}
parent(kim, holly).  
parent(margaret, kim).  
parent(herbert, margaret). 
parent(john, kim).
parent(felix, john).  
parent(albert, felix).
~~~~~

### Predicates Are Just Names: No Meaning Or Implementation

- `parent` is a predicate of **arity** 2 (that takes two arguments)

> - Programmer **mentally** notes that:
>     - `parent(kim, holly)`    **means** `kim` is a "parent-of" `holly`
>     - `parent(margaret, kim)` **means** `margaret` is a "parent-of" `kim`
>     - etc.

## Plan 

### Language

1. Terms
2. Facts
3. **Queries** (Implementation: Unification)
4. Rules
5. Programs (Implementation: Backtracking Search)

### Programming

- Numeric Computation
- Data Structures
- Puzzle Solving

## Language: Queries

TBD

## Plan 

### Language

1. Terms
2. Facts
3. Queries  (Implementation: **Unification**)
4. Rules
5. Programs (Implementation: Backtracking Search)

### Programming

- Numeric Computation
- Data Structures
- Puzzle Solving

## Unification

TBD



## Plan 

### Language

1. Terms
2. Facts
3. Queries  (Implementation: Unification)
4. **Rules**
5. Programs (Implementation: Backtracking Search)

### Programming

- Numeric Computation
- Data Structures
- Puzzle Solving

## Language: Rules

TBD

## Plan 

### Language

1. Terms
2. Facts
3. Queries  (Implementation: Unification)
4. Rules
5. **Programs** (Implementation: Backtracking Search)

### Programming

- Numeric Computation
- Data Structures
- Puzzle Solving

## Programs = Facts + Rules

TBD

## Plan 

### Language

1. Terms
2. Facts
3. Queries  (Implementation: Unification)
4. Rules
5. Programs (Implementation: **Backtracking Search**)

### Programming

- Numeric Computation
- Data Structures
- Puzzle Solving

## Implementation: Backtracking Search

TBD

