# CS 61A Lab 10

## Declarative Programming

In Declarative Programming, we aim to define facts about our universe. With these in place, we can make queries in the form of assertions. The system will then check if the query is true, based on a database of facts. It will inform us of what replacements for the variables will make the query true.

The language we will use is called Logic. An online Logic interpreter is embedded in this lab, which you can use to evaluate logic expressions on this page. You can also use this online Logic interpreter for subsequent homeworks.

Let's review the basics. In Logic, the primitive data types are called symbols: these include numbers and strings. Unlike other languages we have seen in this course, numbers are not evaluated: they are still symbols, but they do not have their regular numerical meaning. Variables in Logic are denoted with a `?` mark preceding the name. So for example, `?x` represents the variable `x`. A relation is a named tuple with a truth value.

The next thing we need to do is begin to define facts about our universe. Facts are defined using a combination that starts with the fact keyword. The first relation that follows is the conclusion, and any remaining relations are hypotheses. All hypotheses must be satisfied for the conclusion to be valid.

(fact (food-chain ?creature1 ?creature2) (eats ?creature1 ?creature3) (eats ?creature3 ?creature2))

Here we have defined the fact for a food chain: If `creature1` eats `creature3`, and `creature3` eats `creature2`, then `creature1` is higher on the food chain than `creature2`.

Simple facts contain only a conclusion relation, which is always true.

(fact (eats shark big-fish)) (fact (eats big-fish small-fish)) (fact (eats domo kittens)) (fact (eats kittens small-fish)) (fact (eats zombie brains)) (fact (append (1 2) (3 4) (1 2 3 4)))

Here we have defined a few simple facts: that in our universe, `sharks` eat `big-fish`, `big-fish` eat `small-fish`, `Domos` eat `kittens`, `kittens` eat `small-fish`, `zombies` eat `brains`, and that the list `(1 2)` appended to `(3 4)` is equivalent to the list `(1 2 3 4)`. Poor kittens.

Queries are combinations that start with the query keyword. The interpreter prints the truth value (either `Success!` or `Failed.`). If there are variables inside of the query, the interpreter will print all possible mappings that satisfy the query.

Each code block that contains a logic expression can be evaluated by clicking into the block and pressing `Ctrl-Enter`. You can also edit the code and evaluate it afterwards by pressing `Ctrl-Enter`.

We're first asking Logic whether a zombie eats brains (the answer is `Success!`) and if a domo eats zombies (the answer is `Failed`). Then we ask whether a zombie can eat something (the answer is `Success!`), and Logic will figure out for us, based on predefined facts in our universe, what a zombie eats. If there are more possible values for what a zombie can eat, then Logic will print out all of the possible values.

### Question 1

In the following box, the `food-chain` facts mentioned above are already defined. Write Logic queries that answers the following questions:

1. Do sharks eat big-fish?
2. What animal is higher on the food chain than small-fish?
3. What animals (if any, or multiple) eat small-fish?
4. What animals (if any, or multiple) eat sharks?
5. What animals (if any, or multiple) eat zombies?
;; Write your queries here, press Ctrl-Enter to evaluate them

### Complex facts

Currently, the `food-chain` fact is a little lacking. A query ```(query (food-chain A B))``` will only output `Success!` if `A` and `B` are separated by only one animal. For instance, if I added the following facts:

(fact (eats shark big-fish)) (fact (eats big-fish small-fish)) (fact (eats small-fish shrimp))

I'd like the `food-chain` to output that shark is higher on the food chain than shrimp. Currently, the `food-chain` fact doesn't do this:

We will define the `food-chain-v2` fact that correctly handles arbitrary length hierarchies. We'll use the following logic:

• Given animals `A` and `B`, `A` is on top of the food chain of `B` if:
• `A` eats `B`, OR
• There exists an animal `C` such that `A` eats `C`, and `C` dominates `B`.

Notice we have two different cases for the `food-chain-v2` fact. We can express different cases of a fact simply by entering in each case one at a time:

;; Click here and press Ctrl-Enter (fact (food-chain-v2 ?a ?b) (eats ?a ?b)) (fact (food-chain-v2 ?a ?b) (eats ?a ?c) (food-chain-v2 ?c ?b)) (query (food-chain-v2 shark shrimp))

Take a few moments and read through how the above facts work, and how it implements the approach we outlined. In particular, make a few queries to `food-chain-v2` -- for instance, try retrieving all animals that dominate shrimp!

Note: In the Logic system, multiple 'definitions' of a fact can exist at the same time (as in `food-chain-v2`) - definitions don't overwrite each other. Instead, they are all checked when you execute a query against that particular fact.

### Recursively-Defined Rules

Next, we will define append in the logic style.

As we've done in the past, let's try to explain how `append` recursively. For instance, given two lists `[1, 2, 3], [5, 7`], the result of `append([1, 2, 3], [5, 7])` is:

`````` + append([2, 3], [5, 7]) => [1, 2, 3, 5, 7]
``````

In Scheme, this would look like:

``````(define (append a b) (if (null? a) b (cons (car a) (append (cdr a) b))))
``````

Thus, we've broken up append into two different cases. Let's start translating this idea into Logic! The first base case is relatively straightforward:

;; Click here and press Ctrl-Enter (fact (append () ?b ?b)) (query (append () (1 2 3) ?what))

So far so good! Now, we have to handle the general (recursive) case:

``````;;                  A        B       C
(fact (append (?car . ?cdr) ?b (?car . ?partial)) (append ?cdr ?b ?partial))
``````

This translates to: the list `A` appended to `B` is `C` if `C` is the result of sticking the CAR of `A` to the result of appending the CDR of `A` to `B`. Do you see how the Logic code corresponds to the recursive case of the Scheme function definition? As a summary, here is the complete definition for append:

(fact (append () ?b ?b )) (fact (append (?a . ?r) ?y (?a . ?z)) (append ?r ?y ?z))

If it helps you, here's an alternate solution that might be a little easier to read:

(fact (car (?car . ?cdr) ?car)) (fact (cdr (?car . ?cdr) ?cdr)) (fact (append () ?b ?b)) (fact (append ?a ?b (?car-a . ?partial)) (car ?a ?car-a) (cdr ?a ?cdr-a) (append ?cdr-a ?b ?partial))

Meditate on why this more-verbose solution is equivalent to the first definition for the append fact.

### Question 2

Using the append fact, issue the following queries, and ruminate on the outputs. Note that some of these queries might result in multiple possible outputs.

; Click here and press Ctrl-Enter (query (append (1 2 3) (4 5) (1 2 3 4 5)))
; Click here and press Ctrl-Enter (query (append (1 2) (5 8) ?what))
; Click here and press Ctrl-Enter (query (append (a b c) ?what (a b c oh mai gawd)))
; Click here and press Ctrl-Enter (query (append ?what (so cool) (this is so cool)))
; Click here and press Ctrl-Enter (query (append ?what1 ?what2 (will this really work)))

### Question 3

Define a fact `(fact (last-element ?lst ?x))` that outputs `Success` if `?x` is the last element of the input list `?lst`.

; YOUR CODE HERE ; Press Ctrl-Enter once you're done typing (query (last-element (a b c) c)) (query (last-element (3) ?x)) (query (last-element (1 2 3) ?x)) (query (last-element (2 ?x) (3)))

Does your solution work correctly on queries such as ```(query (last-element ?x (3)))```? Why or why not?

### Question 4

Write a fact "firsts" that, when input with a list of lists, gives us the first element of each list.

When you finish, the following queries should succeed:

; YOUR CODE HERE ; Press Ctrl-Enter once you're done typing (query (firsts ((1 2 3 4) (2 3 4 5) (1 2 3 4) (1 2 3 2)) ?x)) ; ?x should be (1 2 1 1) (query (firsts ((2 3 4) (3 4 5) (2 3 4) (2 3 2)) ?y)) ; ?y should be (2 3 2 2)

### Question 5

Now, instead of getting us the firsts, let's gather the rests!

When you finish, the following queries should succeed:

; YOUR CODE HERE ; Press Ctrl-Enter once you're done typing (query (rests ((1 2 3 4) (2 3 4 5) (1 2 3 4) (1 2 3 2)) ?x)) ; ?x should be ((2 3 4) (3 4 5) (2 3 4) (2 3 2)) (query (rests ((2 3 4) (3 4 5) (2 3 4) (2 3 2)) ?y)) ; ?y should be ((3 4) (4 5) (3 4) (3 2))

### Sudoku

Assume we have the two facts insert and anagram as follows

(fact (insert ?a ?r (?a . ?r))) (fact (insert ?a (?b . ?r) (?b . ?s)) (insert ?a ?r ?s)) (fact (anagram () ())) (fact (anagram (?a . ?r) ?b) (insert ?a ?s ?b) (anagram ?r ?s))

With our anagram fact, we can write a few more facts to help us solve a 4 by 4 Sudoku puzzle! In our version of Sudoku, our objective is to fill a 4x4 grid such that each column and each row of our simple grid contain all of the digits from 1 to 4.

### Question 6

Let's start by defining our grid using our fact dubbed boxes. Fill in the remainder of the fact.

(fact (boxes ((?a ?b ?c ?d) (?e ?f ?g ?h) (?i ?j ?k ?l) (?m ?n ?o ?p))) (anagram (?a ?b ?e ?f) (1 2 3 4)) ; YOUR CODE HERE )

### Question 7

Next, let's define a fact of specifying the rules for each row in our grid. The input to rows will be the entire 4x4 grid. Fill in rest of the facts in the prompt below:

(fact (rows ())) (fact (rows (?x . ?xs)) ; YOUR CODE HERE )

When you finish, the following queries should return the correct values:

; Press Ctrl-Enter here once you're done typing (query (rows (( 1 2 4 ?a) (?b 3 2 1) (?c 4 3 2) ( 2 4 3 ?d))))

### Question 8

Next, let's define the fact specifying the rules for each column in our grid. Again, remember the the entire grid will be the input to our column query.

(fact (cols (() () () ()))) ; YOUR CODE HERE

When you finish, the following queries should return the correct values:

; Press Ctrl-Enter here once you're done typing (query (cols (( 1 ?b 4 ?d) ( 3 3 2 1) (?a 1 ?c 2) ( 2 4 3 4))))

### Question 9

Now, let's put all of this together to solve our any 4x4 Sudoku grid. Fill in the fact below to do so.

(fact (solve ?grid) ; YOUR CODE HERE )

When you finish, check your solution with the following queries:

; Template for solving Sudoku, don't run this without ; replacing some variables with numbers! ; (query (solve ((?a ?b ?c ?d) ; (?e ?f ?g ?h) ; (?i ?j ?k ?l) ; (?m ?n ?o ?p)))) ; Press Ctrl-Enter here once you're done typing (query (solve (( 1 ?b 4 ?d) (?e 3 ?g 1) (?i 4 ?k 2) ( 2 ?n 3 ?p))))

### Question 10

Solve the following sudoku puzzle with the new solver that you built!

Tip: it's a good idea to save your code in one place before trying this, since this will take a long time. Also, press Ctrl-Enter only once and be prepared to wait ;)

``````+-+-+-+-+
|3| | |1|
+-+-+-+-+
|1| | | |
+-+-+-+-+
| | | | |
+-+-+-+-+
| | |2| |
+-+-+-+-+
``````