Showing posts with label Peter Norvig. Show all posts
Showing posts with label Peter Norvig. Show all posts

Thursday, March 16, 2017

My theorem-prover is (basically) working

My resolution theorem prover is working: find the documentation and code here.

My initial, rather simple test data concerns Sally Fowler's situation aboard the battleship MacArthur ('The Mote in God's Eye').



Who does Sally like: ←  (LIKES SALLY ?WHO)

Well, here are the Prolog-style facts.
 (LIKES ROD HORVATH) ←
 (LIKES SALLY RENNER) ←
 (LIKES SALLY ROD) ←
 (LIKES HARDY RENNER) ←
 (LIKES HARDY ROD) ←
 (AMUSING HARDY) ←
 (LIKES HORVATH MOTIES) ←
 (LIKES SALLY ?X) ← (LIKES ?X MOTIES)
 (LIKES ROD ?X) ← (LIKES ?X RENNER) (LIKES ?X ROD)
 (LIKES ?X ?Y) ← (AMUSING ?Y) (LIKES ROD ?Y)
 (LIKES ?X ?X) ←
Based on the above, the theorem-prover offers the following five responses. I doubt you are overwhelmed ... but then, test data is designed to be easy to understand.
1, Because everyone likes themselves, Sally likes Sally.

2. Because it's mentioned Sally likes Rod, she does.

3. Because it's mentioned Sally likes Renner, she does.

4. Sally likes those who like Moties. Moties like Moties because everyone likes themselves. So Sally likes Moties.

5. Sally likes people who like Moties. Horvath like Moties.  So Sally likes Horvath.
More precisely, after a little editing (inserted line-breaks), this is what was printed out.
((((<- ((LIKES SALLY SALLY))))
  (((13 NIL NIL) ((LIKES ?X ?X) <-))
   ((14 NIL NIL) (<- ((LIKES SALLY ?WHO))))
   ((19 14 13) +EMPTY-CLAUSE+)))

 (((<- ((LIKES SALLY ROD))))
  (((5 NIL NIL) ((LIKES SALLY ROD) <-))
   ((14 NIL NIL) (<- ((LIKES SALLY ?WHO))))
   ((16 14 5) +EMPTY-CLAUSE+)))

 (((<- ((LIKES SALLY RENNER))))
  (((4 NIL NIL) ((LIKES SALLY RENNER) <-))
   ((14 NIL NIL) (<- ((LIKES SALLY ?WHO))))
   ((15 14 4) +EMPTY-CLAUSE+)))

 (((<- ((LIKES SALLY MOTIES))))
  (((13 NIL NIL) ((LIKES ?X ?X) <-))
   ((10 NIL NIL) ((LIKES SALLY ?X) <- ((LIKES ?X MOTIES))))
   ((14 NIL NIL) (<- ((LIKES SALLY ?WHO))))
   ((17 14 10) (<- ((LIKES ?WHO MOTIES))))
   ((24 17 13) +EMPTY-CLAUSE+)))

 (((<- ((LIKES SALLY HORVATH))))
  (((9 NIL NIL) ((LIKES HORVATH MOTIES) <-))
   ((10 NIL NIL) ((LIKES SALLY ?X) <- ((LIKES ?X MOTIES))))
   ((14 NIL NIL) (<- ((LIKES SALLY ?WHO))))
   ((17 14 10) (<- ((LIKES ?WHO MOTIES))))
   ((20 17 9) +EMPTY-CLAUSE+)))

Figure 1
---

Q&A.

1. Isn't this just Prolog?

Prolog is encountered as a black box. You provide a program and a query (as above) and you get back bindings, like this:
?- likes(sally, W).

W = sally;
W = rod;
... and so on

If you want proofs, to add the 'occurs check' or to change the order in which resolution steps are tried (the search strategy) - well tough: all those things are both fixed and opaque in Prolog. To make them explicit for modification, you have to write an explicit theorem-prover in Prolog (which can of course be done).

2. You are using Horn clauses?

Yes. I initially thought to implement a general clausal prover, but Horn clauses make the resolution step particularly simple (just one positive literal to match) and you lose neither generality nor expressive power. But since everything in the code is both modular and explicit, it would be easy to extend the program.

3. The style is functional?

Yes. Resolution theorem provers on the Internet are heavily optimised with clever, imperative algorithms and direct access data structures such as hash tables. This makes the code efficient but obscure - very hard to understand.

I didn't want to do that. This is a tool-kit and I'm not trying to create thousands of logical inferences per second. My intended application area (simple inference over an ever-changing knowledge-base for a chatbot) never requires massive inferential chains so clarity and easy modifiability was my objective.

4. What was hard?

The program is architected at three levels.

(a) Unification

This is basically already quite modular and straightforward. I re-used Peter Norvig's code.

(b) Resolution

Binary resolution itself - specially with Horn clauses - is a straightforward procedure - as you will see when I publish the code. There are some subtleties with bindings and substitutions, but once you realise that resolution is fundamentally a local operation it's not too difficult.

(c) Control and proof construction

The process of creating new goals and resolving them with the axioms is somewhat complex although again, sticking with Horn clauses makes it a lot easier: just think of a naive Prolog execution model.

However, if you want to return proofs, you need to number the axioms and number-and-archive goals as you process them, capturing the resulting tree of inferences. At the end, for each empty-clause = successful proof, you need to trace that index-tree backwards to recover the proof steps. That's what created figure 1 above. I found it a bit intricate.

5. What's next?

In theory you can do anything with a theorem-prover (Prolog being the existence proof) but it's not necessarily the best architecture. For a planner, where state changes are part of the problem definition, I need to adapt the tool-kit to a design centred around actions with pre- and post-condition in the context of a goal-state and an updating world-state. Such a dynamic model can be used both for actions in a (virtual) world and conversation planning via speech acts.

The theorem-prover remains optimal as a separate module, managing the crystallized knowledge base using inference to draw conclusions - for example to drive questions and answers.

I'm thinking of using the already-programmed Eliza front-end as a robust conversational interface. Doesn't matter if it's bluffing some of the time if it can use learning, inference and planning often enough.

Onwards to the GOFAI smart chatbot ...

---

Here is the documentation and code.

Saturday, February 18, 2017

Diary: my day with a Prolog interpreter in Lisp

The subject: implementing a Prolog interpreter in Common Lisp, using an excellent - if rather old-fashioned - textbook as my guide. I had copied-and-pasted the code across (it never quite works first time) and was debating this morning: finally get Peter Norvig's code to run, or strike out in my own direction?

There's a lot in Chapter 11 of "Paradigms of Artificial Intelligence programming" to be wary of:
  • For efficiency reasons he stores the clauses on clause-head-predicate property lists
  • He uses destructive operations such as nconc
  • The resolution inference step and depth-first control strategy are interwoven.
I'd prefer to keep the clause database as an explicit object to be transformed and analysed throughout the proof. I'd also like to modularise the 'which clauses to try to resolve next' strategy, trying different things such as unit preference, set-of-support, hyperresolution. And it would be good to extract a proof tree, not just the final question-answering bindings.

All these things demand a rewrite.

But I was glad I persevered, because Peter Norvig's code finally came good this afternoon and I was able to successfully run it on a serious logic puzzle - the Zebra problem.

Where it ran remarkably quickly - forty times faster than in Dr Norvig's textbook-writing days. I was reminded of AI programming back in the late 1980s, when everything was slow and hard.

I imagined him developing his code on some ancient VAX 11/780 (as I used to do).

A simple Prolog interpreter in Lisp

I happen to think that the code for 'prove' et al below is extremely opaque. You will search in vain for any clear modularisation into:
  • Resolution operation
  • Depth-first control strategy
  • Bindings and solution management.
For conceptual, pedagogical and tool-creation reasons, a rational reconstruction is necessary. When this is completed, I will post a link to the rewritten - and hopefully clearer code - here.

; ---- Lisp code starts here ---
;
;;;  Prolog in Lisp:  February 14th 2017 - February 18th 2017
;;;
;;;  From Peter Norvig's book: Chapter 11
;;; "Paradigms of Artificial Intelligence Programming"
;;;
;;; Unification, Prolog, Resolution, inference control strategies
;;;
;;; Posted:
; http://interweave-consulting.blogspot.co.uk/2017/02/a-simple-prolog-interpreter-in-lisp.html
;;;
;;;  Reminder: (how to load and access files)
;;;
; (load  "C:\\Users\\HP Owner\\Google Drive\\Lisp\\Prog-Prolog\\Prolog-in-Lisp.lisp")

;;;
;;; --- Unification ---
;;;
;;;  Bindings: a list of dotted pairs created by unify

(defconstant +fail+ nil "Indicates pat-match failure.")

(defconstant +no-bindings+ '((t . t))
"Indicates pat-match success but with no variables.")

(defun variable-p (x)    ; Symbol -> Bool
  "Is x a variable, a symbol beginning with '?'"
  (and (symbolp x) (equal (char (symbol-name x) 0) #\? )))

(defun get-binding (var bindings)
  "Find a (variable . value) pair in a binding list."
  (assoc var bindings))

(defun binding-val (binding)
  "Get the value part of a single binding."
  (cdr binding))

(defun lookup (var bindings)
  "Get the value part (for var) from a binding list."
  (binding-val (get-binding var bindings) ))

(defun extend-bindings (var val bindings)
  "Add a (var . value) pair to a binding list, remove (t . t)"
  (cons (cons var val) (if (equal bindings +no-bindings+) nil bindings)))

(defparameter *occurs-check* t "Should we do the occurs check? If yes, t")

(defun unify (x y &optional (bindings +no-bindings+))   ; -> Bindings
  "See if x and y match with given bindings"
  (cond ((eq bindings +fail+) +fail+)
        ((eql x y) bindings)
        ((variable-p x) (unify-variable x y bindings))
        ((variable-p y) (unify-variable y x bindings))
        ((and (consp x) (consp y))
         (unify (rest x) (rest y)
                (unify (first x) (first y) bindings) ) )
        (t +fail+) ) )

(defun unify-variable (var x bindings)              ; -> Bindings
  "Unify var with x, using (and maybe extending) bindings"
  (cond ((get-binding var bindings)
                  (unify (lookup var bindings) x bindings))
            ((and (variable-p x) (get-binding x bindings))
                  (unify var (lookup x bindings) bindings))
              ((and *occurs-check* (occurs-check var x bindings))
                  +fail+)
            (t (extend-bindings var x bindings))))

(defun occurs-check (var x bindings)             ; -> Bool
  "Does var occur anywhere 'inside x'? Returns t if it does (so fail)"
  (cond ((eq var x) t)
        ((and (variable-p x) (get-binding x bindings))
         (occurs-check var (lookup x bindings) bindings))
        ((consp x) (or (occurs-check var (first x) bindings)
                       (occurs-check var (rest x) bindings)))
        (t nil)))


(defun unifier (x y )
  "Return something that unifies with both x and y (or +fail+)"
  (subst-bindings (unify x y) x ) )


(defun subst-bindings (bindings x)   ; Bindings x Term -> Term
  "Substitute the value of variables in bindings into x,
taking recursively bound variables into account"
  (cond ((eql bindings +fail+) +fail+ )
        ((eql bindings +no-bindings+) x)
        ((and (variable-p x) (get-binding x bindings))
              (subst-bindings bindings (lookup x bindings) ))
        ((atom x) x)
        ( t (cons (subst-bindings bindings (car x))
                        (subst-bindings bindings (cdr x )) ) ) ) )


;;; -------------------------- Theorem Prover -----------------
;;;
;;; Clauses are represented as (head . body) cons cells: example clauses
;;;
;;;  ( (member ?item (?item . rest))) )                         ; fact
;;;  ( (member ?item (?x . ?rest)) . ((member ?item ?rest)))    ; rule


(defun clause-head (clause) (first clause))     ; Clause -> Literal

(defun clause-body (clause) (rest clause))      ; Clause -> Literal-list

;; Clauses are stored on the predicate's plist

(defun get-clauses (pred) (get pred 'clauses)) ; symbol -> Clause-list

(defun predicate (literal) (first literal))    ; Literal -> Symbol (predicate)

(defvar *db-predicates* nil
  "A list of all predicates stored in the database")

(defun replace-?-vars (exp)
  "Replace any ? within exp with a var of the form ?123"
  (cond ((eq exp '?) (gensym "?"))
        ((atom exp) exp)
        (t (cons (replace-?-vars (first exp))
                 (replace-?-vars (rest exp))) ))  )


(defun add-clause (clause)
  "Add a clause to the data base, indexed by head's predicate"
  ;; The predicate must be a non-variable symbol.
  (let* ((clause1 (replace-?-vars clause))
         (pred (predicate (clause-head clause1))))
    (assert (and (symbolp pred) (not (variable-p pred))))
    (pushnew pred *db-predicates*)
    (setf (get pred 'clauses)
          (append (get-clauses pred) (list clause1))) pred) )   ; changed nconc to append

; (setf clause '((P ?x ?y) . ((Q ?x ?y))))
; (add-clause clause)                       ; => P
; *db-predicates*                           ; => (P)
; (get 'P 'clauses)                         ; (((P ?X ?Y) (Q ?X ?Y)))

(defun show-all-clauses ()   ; *db-predicates*  -> Clause-list    (new function)
    "Retrieve all the clauses in the knowledge-base"
     (apply #'append (mapcar #'get-clauses *db-predicates*)))

(defun clear-db ()
  "Remove all clauses (for all predicates) from the database"
  (mapc #'clear-predicate *db-predicates*))

(defun clear-predicate (predicate)
  "Remove the clauses for a single predicate"
  (setf (get predicate 'clauses) nil) )

(defun test ()
  (clear-db)
  (setf *db-predicates* nil)
  (add-clause '((likes Kim Robin)))
  (add-clause '((likes Sandy Lee)))
  (add-clause '((likes Sandy Kim)))
  (add-clause '((likes Robin cats)))
  (add-clause '((likes Sandy ?x) (likes ?x cats)))
  (add-clause '((likes Kim ?x) (likes ?x Lee) (likes ?x Kim)))
  (add-clause '((likes ?x ?x)))
  (format t "~&Predicate database *db-predicates* = ~a" *db-predicates*)
  (terpri)
  (pprint (show-all-clauses))
  (terpri)
  (prove '(likes Sandy ?who) +no-bindings+) )

(defun prove (goal b)    ; Literal x Bindings -> Bindings
  "Return a list of possible solutions to goal"
  (let ((kb-clauses (get-clauses (predicate goal))))  ; kb clauses which match goal
    (apply #'append (mapcar #'(lambda (kb-clause1)
                                (let* ((kb-clause       (rename-variables kb-clause1))
                                       (kb-clause-head  (clause-head kb-clause))
                                       (kb-clause-body  (clause-body kb-clause))
                                       (goal-bindings   (unify goal kb-clause-head b)))
                                  (prove-all kb-clause-body goal-bindings)))
                            kb-clauses)) ) )

(defun prove-all (goals goal-bindings) ; Literal-list x Bindings -> Bindings
  "Return a list of solutions to the conjunction of goals"
  (cond ((eql goal-bindings +fail+) +fail+)
        ((null goals) (list goal-bindings))
        (t  (let* ((next-bindings (prove (car goals) goal-bindings)))
              (apply #'append (mapcar #'(lambda (b) (prove-all (cdr goals) b))
                                      next-bindings)) ) ) ) )


(defun rename-variables (x)       ; clause -> clause (with vars renamed)
  "Replace all variables in x with new ones"
  (sublis (mapcar #'(lambda (var) (cons var (gensym (string var))))
                  (variables-in x))
          x))

;;; --- Example ---
#|
(add-clause '((likes Kim Robin)))
(add-clause '((likes Sandy Lee)))
(add-clause '((likes Sandy Kim)))
(add-clause '((likes Robin cats)))
(add-clause '((likes Sandy ?x) (likes ?x cats)))
(add-clause '((likes Kim ?x) (likes ?x Lee) (likes ?x Kim)))
(add-clause '((likes ?x ?x)))

(prove '(likes Sandy ?who) +no-bindings+)   ; =>

; (((?WHO . LEE))
;  ((?WHO . KIM))
;  ((#:?X846 . ROBIN)
;  (?WHO . #:?X846))
;  ((#:?X850 . CATS) (#:?X847 . CATS) (#:?X846 . SANDY) (?WHO . #:?X846))
;  ((#:?X855 . CATS) (#:?X846 . #:?X855) (?WHO . #:?X846))
;  ((?WHO . SANDY) (#:?X857 . SANDY)))
;
; - End Example
|#

;;; --- Prolog-like macros - defined also in Zebra-Puzzle ---
;
(defmacro <- (&rest clause)
  "Add a clause to the database"
  `(add-clause ',clause))

; (macroexpand-1 '(<- (likes Kim Robin)))    ; =>
; (ADD-CLAUSE (QUOTE ((LIKES KIM ROBIN))))   ; which is correct.

 (defmacro ?- (&rest goals) `(top-level-prove ',(replace-?-vars goals)))

; (macroexpand-1 '(?- goals))

;;; --- Prove removing spurious bindings ---

(defun variables-in (exp)
  "Return a list of all the variables in exp"
  (unique-find-anywhere-if #'variable-p exp))

(defun unique-find-anywhere-if (predicate tree &optional found-so-far)
  "Return a list of leaves of tree satisfying predicate, with duplicates removed"
  (if (atom tree)
      (if (funcall predicate tree) (adjoin tree found-so-far) found-so-far)
      (unique-find-anywhere-if predicate (first tree)
                            (unique-find-anywhere-if predicate (rest tree) found-so-far)
 )))

(defun top-level-prove (goals)
  "Prove the goals, and print variables readably"
  (show-prolog-solutions (variables-in goals) (prove-all goals +no-bindings+)))

(defun show-prolog-solutions (vars solutions)
  "Print the variables in each of the solutions"
  (if (null solutions)
      (format t "~&No.")
      (mapc #'(lambda (solution) (show-prolog-vars vars solution)) solutions))
  (values))

(defun show-prolog-vars (vars bindings)
  "Print each variable with its binding"
  (if (null vars)
      (format t "~&Yes")
    (dolist (var vars)
      (format t "~&~a = ~a" var (subst-bindings bindings var))))
  (princ ";"))

;
;;; --- Zebra Puzzle  ---
; (load  "C:\\Users\\HP Owner\\Google Drive\\Lisp\\Prog-RTP\\Zebra-Puzzle.lisp")
;
;;; --- Zebra Puzzle  ---
;
#| Begin comments

Here is an example of something Prolog is very good at: a logic puzzle. There are
fifteen facts, or constraints, in the puzzle:

1. There are five houses in a line, each with an owner, a pet, a cigarette, a drink,
and a color.
2. The Englishman lives in the red house.
3. The Spaniard owns the dog.
4. Coffee is drunk in the green house.
5. The Ukrainian drinks tea.
6. The green house is immediately to the right of the ivory house.
7. The Winston smoker owns snails.
8. Kools are smoked in the yellow house.
9. Milk is drunk in the middle house.
10. The Norwegian lives in the first house on the left.
11. The man who smokes Chesterfields lives next to the man with the fox.
12. Kools are smoked in the house next to the house with the horse.
13. The Lucky Strike smoker drinks orange juice.
14. The Japanese smokes Parliaments.
15. The Norwegian lives next to the blue house.

The questions to be answered are: who drinks water and who owns the zebra?

End comments
|#

(<- (member ?item (?item . ?rest )))
(<- (member ?item (?x . ?rest) ) (member ?item ?rest))

(<- (nextto ?x ?y ?list) (iright ?x ?y ?list))
(<- (nextto ?x ?y ?list) (iright ?y ?x ?list))

(<- (iright ?left ?right (?left ?right . ?rest)))
(<- (iright ?left ?right (?x . ?rest)) (iright ?left ?right ?rest))
(<- (= ?x ?x))

;; Each house is of the form:
;; (house nationality pet cigarette drink house-color)
;; ?h is the variable representing the list of the five houses

(<- (zebra ?h ?w ?z)

  (= ?h ((house norwegian ? ? ? ?) ? (house ? ? ? milk ?) ? ? ) )   ; 1, 10, 9
  (member (house englishman ? ? ? red) ?h)                                 ; 2
  (member (house spaniard dog ? ? ?) ?h)                                     ; 3
  (member (house ? ? ? coffee green) ?h)                                     ; 4
  (member (house ukrainian ? ? tea ?) ?h)                                    ; 5
  (iright (house ? ? ? ? ivory)                                                        ; 6
          (house ? ? ? ? green) ?h)
  (member (house ? snails winston ? ?) ?h)                                  ; 7
  (member (house ? ? kools ? yellow) ?h)                                     ; 8
  (nextto (house ? ? chesterfield ? ?)                                             ; 11
          (house ? fox ? ? ?) ?h)
  (nextto (house ? ? kools ? ?)                                                       ; 12
          (house ? horse ? ? ?) ?h)
  (member (house ? ? luckystrike orange-juice ?) ?h)                  ; 13
  (member (house japanese ? parliaments ? ?) ?h)                       ; 14
  (nextto (house norwegian ? ? ? ?)                                              ; 15
          (house ? ? ? ? blue) ?h)

;; Now for the questions:

   (member (house ?w ? ? water ?) ?h)                                        ; Q1
   (member (house ?z zebra ? ? ?) ?h) )                                        ; Q2

; Here's the query

;  (?- (zebra ?houses ?water-drinker ?zebra-owner))

; .. and here's the result

; ?HOUSES = ((HOUSE NORWEGIAN FOX KOOLS WATER YELLOW)
; (HOUSE UKRAINIAN HORSE CHESTERFIELD TEA BLUE)
; (HOUSE ENGLISHMAN SNAILS WINSTON MILK RED)
; (HOUSE SPANIARD DOG LUCKYSTRIKE ORANGE-JUICE IVORY)
; (HOUSE JAPANESE ZEBRA PARLIAMENTS COFFEE GREEN))
; ?WATER-DRINKER = NORWEGIAN
; ?ZEBRA-OWNER = JAPANESE.
; No.
;
; ------------------------------------------------------------------------------------------------------------
; The Zebra Puzzle is at:
;
;  http://interweave-consulting.blogspot.co.uk/2017/02/the-zebra-puzzle-prolog-in-lisp.html
;
;                                            ----------------- End ------------------

The Zebra Puzzle (Prolog in Lisp)

I am delighted to have got Peter Norvig's Lisp interpreter for Prolog working (in its simplest form) from Chapter 11 of his book, "Paradigms of Artificial Intelligence programming".



I tested it on his Zebra puzzle, where he states:
"This took 278 seconds, and profiling (see page 288) reveals that the function prove was called 12,825 times. A call to prove has been termed a logical inference, so our system is performing 12825/278 = 46 logical inferences per second, or LIPS.

Good Prolog systems perform at 10,000 to 100,000 LIPS or more, so this is barely limping along."
On my Windows 10 HP laptop, the computation took 7 seconds with 29,272 calls to 'prove'.

I guess that's 4,182 LIPS for compiled Lisp from LispWorks - program totally unoptimised.

His book is rather old (1992).

---

The Zebra puzzle

"Here is an example of something Prolog is very good at: a logic puzzle. There are fifteen facts, or constraints, in the puzzle:
1. Five houses in a line, each with an owner, a pet, a cigarette, a drink, and a color.
2. The Englishman lives in the red house.
3. The Spaniard owns the dog.
4. Coffee is drunk in the green house.
5. The Ukrainian drinks tea.
6. The green house is immediately to the right of the ivory house.
7. The Winston smoker owns snails.
8. Kools are smoked in the yellow house.
9. Milk is drunk in the middle house.
10. The Norwegian lives in the first house on the left.
11. The man who smokes Chesterfields lives next to the man with the fox.
12. Kools are smoked in the house next to the house with the horse.
13. The Lucky Strike smoker drinks orange juice.
14. The Japanese smokes Parliaments.
15. The Norwegian lives next to the blue house.
The questions to be answered are: who drinks water and who owns the zebra?"

The translation into Prolog in Lisp uses a Lisp-like syntax for Prolog facts and rules (both are clauses). Here's the Prolog 'program' coding the above problem.

;;; --- Lisp code follows - comments from Norvig's book  ---
;;;
;;; To solve this puzzle, we first define the relations nextto (for "next to") and
;;;  iright (for 'immediately to the right of'). They are closely related to member,
;;; which is repeated here.
;;;

(<- (member ?item (?item . ?rest )))
(<- (member ?item (?x . ?rest) ) (member ?item ?rest))

(<- (nextto ?x ?y ?list) (iright ?x ?y ?list))
(<- (nextto ?x ?y ?list) (iright ?y ?x ?list))

(<- (iright ?left ?right (?left ?right . ?rest)))
(<- (iright ?left ?right (?x . ?rest)) (iright ?left ?right ?rest))
(<- (= ?x ?x))

;;; We also defined the identity relation, =. It has a single clause that says that any x is
;;; equal to itself. One might think that this implements eq or equal. Actually, since
;;; Prolog uses unification to see if the two arguments of a goal each unify with ?x, this
;;; means that = is unification.

;;; Each house is of the form:
;;; (house nationality pet cigarette drink house-color)
;;; ?h is the variable representing the list of the five houses

(<- (zebra ?h ?w ?z)

  (= ?h  ((house norwegian ? ? ? ?) ? (house ? ? ? milk ?) ? ? ) )              ; 1, 10, 9
  (member (house englishman ? ? ? red) ?h)                                             ; 2
  (member (house spaniard dog ? ? ?) ?h)                                                 ; 3
  (member (house ? ? ? coffee green) ?h)                                                  ; 4
  (member (house ukrainian ? ? tea ?) ?h)                                                 ; 5
  (iright (house ? ? ? ? ivory)                                                                     ; 6
             (house ? ? ? ? green) ?h)
  (member (house ? snails winston ? ?) ?h)                                               ; 7
  (member (house ? ? kools ? yellow) ?h)                                                 ; 8
  (nextto (house ? ? chesterfield ? ?)                                                         ; 11
             (house ? fox ? ? ?) ?h)
  (nextto (house ? ? kools ? ?)                                                                   ; 12
              (house ? horse ? ? ?) ?h)
  (member (house ? ? luckystrike orange-juice ?) ?h)                              ; 13
  (member (house japanese ? parliaments ? ?) ?h)                                   ; 14
  (nextto (house norwegian ? ? ? ?)                                                          ; 15
              (house ? ? ? ? blue) ?h)

;; Now for the questions:

   (member (house ?w ? ? water ?) ?h)                                                     ; Q1
   (member (house ?z zebra ? ? ?)  ?h) )                                                   ; Q2

; Here's the query

  (?- (zebra ?houses ?water-drinker ?zebra-owner))

; .. and here's the result

?HOUSES = ((HOUSE NORWEGIAN FOX KOOLS WATER YELLOW)
                       (HOUSE UKRAINIAN HORSE CHESTERFIELD TEA BLUE)
                       (HOUSE ENGLISHMAN SNAILS WINSTON MILK RED)
                       (HOUSE SPANIARD DOG LUCKYSTRIKE ORANGE-JUICE IVORY)
                       (HOUSE JAPANESE ZEBRA PARLIAMENTS COFFEE GREEN))
?WATER-DRINKER = NORWEGIAN
?ZEBRA-OWNER = JAPANESE;

---

I'll publish the Lisp code for the Prolog interpreter separately (here):

http://interweave-consulting.blogspot.co.uk/2017/02/a-simple-prolog-interpreter-in-lisp.html


Wednesday, February 15, 2017

The problem of dialogue as regards chatbots

Me: "So here's my plan."

Clare: "OK."

Me: "I've copied Peter Norvig's chapter 11 code for a Prolog interpreter in Lisp into a Notepad file. Unfortunately copying from PDF introduces all kinds of formatting errors, so it takes a while to get it into a compilable state."

Clare: "?"

Me: "I need to work through his main functions - principally to exactly understand his unification algorithm to start with. I may modify the code a bit, make it more transparent."

Clare: "??"

Me (oblivious): "And then I'm not sure I like the way he's storing clauses as plists on the clause head predicate. I think an assoc list would be clearer, if less efficient. Also, I need to do a few paper and pen examples to understand exactly the rationale for variable-renaming between clauses during resolution."

Clare: "???"

Me: "I'll get his standard Prolog depth-first search to work first of course. But I think it would be a good idea to explicitly break out the resolution procedure as a standalone function, and then parameterise the proof procedure by a range of possible search methods including breadth-first and best-first."

Clare: "????"

Me: "Of course, all this is just to get a series of tools in place for my speech-act planner, the one that's going to make my chatbot able to steer a conversation."

Clare: "?????"

Me: "I really think this could be a stellar app. I can see it on Google Play. The trouble is, 'in the knowledge lies the power' is just as relevant here and I might need to spend way too much time just data-filling various knowledge-bases, ... hmm, unless I can get it to safely learn from users. That's where Google does have an advantage ..."

[Pause]

Clare: "Is that Mr Bullfinch I see on the fat block?"

Saturday, February 11, 2017

Diary: snow + books + chatbot backstory

We last had snow here back in December 2010 (when it was heavy). This morning only the lightest dusting .. and as I write, it's gone.

A light dusting of snow in our garden this morning
---

This new book by Dalton Conley and Jason Fletcher should be arriving today.

Amazon link

Expect a review in due course if it's any good.

Update: it's now arrived and I've had a peek. The authors are both sociology professors, which rings alarm bells. And they have an agenda. They're here to defend the standard social science model against the unsettling results of recent DNA sequencing programs and GWAS (genome-wide association studies). Their idea is to make the most minimal concessions to evidence while still preserving the traditional social-sciences advocacy-based value system. So races don't exist, racial genetic differences in cognition don't exist, and most else which might disturb the liberal agenda of the irrelevance of genetics for outcomes is explained away.

Depressing.

[Update (Sunday): my first impressions were wrong. The book is both more honest and more erudite than had appeared from a first skim. The authors may be billed as sociologists but they are both genetics research practitioners. Once you have absorbed the theory and methodology, it's harder to be agenda-driven - if you're honest. I think a review will be in order once I've finished.]

[Update (Monday): Finished. It was as my first impressions. A sophisticated attempt to save the SSSM from those pesky geneticists. Sophistry rules: don't waste your money. Review here.]

---

Genetics, especially human genomics, is the one area of contemporary science most at odds with prevailing western ideology. Most of the time this didn't matter - you can believe whatever you like if it has no practical consequences: in fact most human beliefs are like that.

But with emergent technologies for DNA sequencing, embryo selection and genome-editing, the science soon will matter. You will be able, in principle, to improve attributes (such as the health, emotional stability and intelligence) of your children. The issues will be regulation. cost and your desire to do so.

I anticipate, with no joy, decades of screaming hysteria.

I'm also working my way through Sean Carroll's book on entropy and the 'Past Hypothesis',



and Stephen Cohen's excellent biography of Bukharin,




not to mention Scott Bakker's 'Prince of Nothing'.




It's hard to timeshare: particularly when one is programming.

Incidentally, just as it is said that no-one feels hunger pangs when stepping out of a plane to do a parachute jump, an afternoon programming tends to obscure the fact you've skipped lunch. Just over 68kg this morning (10st 10.4lb) as the abdominal bulge recedes somewhat.

I'm pleased.

---

Just a short note-to-self about the chatbot stuff. The next thing (after the recent Eliza-style vacuity) is to capture the 'aboutness' of conversation. In chatting, each conversational partner brings some backstory to a discussion.

The essence of being an effective chatbot is:
  1. Manage a dynamic back-story of your own,
  2. Engage with the backstory of your human conversational partner.
If the chatbot is a cat, the backstory can be quite constrained - for example, nocturnal adventures in the garden with other cats, badgers, voles, birds, food and vomiting. I was looking at Peter Norvig's GPS reconstruction (previously discussed here) as a possible route to writing a dynamic simulation model.

The various entities I mentioned (cats, badgers, voles, ..) should have actions which require their preconditions in the garden knowledge-base (KB) to hold, and which then assert their post conditions in the next KB iteration. Make actions probabilistic and you've got an interesting simulation.

GPS doesn't quite work in this forward-chaining mode so it's not a case of just adapting his existing code. But the Eliza pattern-matching engine can be the reusable heart of it.

Friday, February 10, 2017

So I posted a lot of Lisp here

OK, I know that most of you won't want to hack through pages of Lisp code and pages of Lisp rules. The post which is worth a look at is the example in use.

This shows the strength and weakness of the vanilla Eliza in action.

---

It's tempting, and even conventional, to scoff at Eliza. Peter Norvig says in Chapter 5.4 of his "Paradigms of Artificial Intelligence Programming":
" In the end, it is the technique that is important - not the program. ELIZA has been "explained away" and should rightfully be moved to the curio shelf. Pattern matching in general remains important technique, and we will see it again in subsequent chapters. The notion of a rule-based translator is also important. The problem of understanding English (and other languages) remains an important part of AI. Clearly, the problem of understanding English is not solved by ELIZA."

But the Eliza engine is a very good place to start.

---

What next?



The inadequacies of pseudo-human interlocutors are more forgivable in an animal. I'm going to craft a rule set for our dear, departed pet using the existing Eliza engine: Shadow v. 1.0.

Then it's back to Peter Norvig for his Prolog interpreter in Lisp (chapter 11). This will give me a unification algorithm and a resolution procedure.

My proposed architecture is to use the Eliza engine for input-output and have a Prolog-style knowledge-representation and inference-engine at the back.

In theory, the knowledge-based could be data-filled with rather tedious Q&A - the kind of thing which gives chatbots a bad name - but it's more pleasant for the user to have an initial registration procedure in which the user just tells the system about the domain of interest. For example, details of family and friends. Yes, I'm aware of privacy issues: you ask, in the age of Facebook?

The final area of architecture which I've been thinking about is the topic of conversation. This relates to the information and issues currently being talked about which drive the conversation forward. In Eliza it's basically in the hands of the user: there is no chatbot control mechanism.

But we can do better once we can do inference.

Watch this space.

Common Lisp code for the Eliza chatbot

#| This is the Peter Norvig (slightly adapted) code for the vanilla Eliza chatbot. For the rules see here. For an example of the program in action, see here.

This code should run if copied and pasted into a Common Lisp system, provided the rules file is also available and the 'Load' command below suitably amended - or just copy and paste the rules at the end of this file.

---
|#

;;; Eliza:  February 7th 2017 - February 10th 2017
;;;
;;; From Peter Norvig's book: Chapter 5
;;; "Paradigms of Artificial Intelligence Programming"
;;;
;;; Pattern matching, patterns and dialogue manager
;;;
;;; Posted:
; http://interweave-consulting.blogspot.co.uk/2017/02/common-lisp-code-for-eliza-chatbot.html
;;;
;;;  Reminder: (how to load and access files)
;;;
; (load  "C:\\Users\\HP Owner\\Google Drive\\Lisp\\Prog-Eliza\\Eliza.lisp")

(load  "C:\\Users\\HP Owner\\Google Drive\\Lisp\\Prog-Eliza\\Eliza-Rules.lisp")


;;; ---Patterns and input ---
;;;
;;; A pattern is a list of:-  segment-variable-lists, symbols or variables.
;;; An input is a list of symbols (without variables).
;;;
;;; Test pattern match in simple cases
;;;
; (setf *inp1* '(I need a vacation))
; (setf *pat1* '(I need a ?x))
; (pat-match *pat1* *inp1)
;
; ... when matched, should return a binding '((?X . vacation))
;
; (setf *inp2* '(Shadow and I need a holiday))
; (setf *pat2* '((?* ?U) need (?* ?V)) )
;
;;; --- Binding constants ---

(defconstant +fail+ nil "Indicates pat-match failure.")

(defconstant +no-bindings+ '((t . t))
"Indicates pat-match success but with no variables.")

(defconstant +example-bindings+
   '((?X . (the cat)) (?Y . (sat on)) (?Z the mat))  )

;;; --- BINDINGS a list of (var . value) dotted pairs ---
;;;
; a list of the form (?* ?variable-name) denotes a segment variable.
; Eg:  (pat-match '((?* ?p) need (?* ?X)) '(Mr Hulot and I need a vacation))
; gives ((?P MR HULOT AND I) (?X A VACATION)) .. as the (dotted pair) binding.

(defun get-binding (var bindings)
  "Find a (variable . value) pair in a binding list."
  (assoc var bindings))

(defun binding-val (binding)
  "Get the value part of a single binding."
  (cdr binding))

(defun lookup (var bindings)
  "Get the value part (for var) from a binding list."
  (binding-val (get-binding var bindings) ))

(defun extend-bindings (var val bindings)
  "Add a (var . value) pair to a binding list."
  (acons var val bindings))

(defun variable-p (x)    ; SYMBOL -> Bool
  "Is x a variable, a symbol beginning with '?' "
  (and (symbolp x) (equal (char (symbol-name x) 0) #\? )))
 
(defun starts-with (list x)  ; SYMBOL-list x SYMBOL -> Bool
  "Is this a non-empty list whose first element is x?"
  (and (consp list) (eql (car list) x)) )
 
;;; --- Pattern Matcher ---

; pat-match: PATTERN x INPUT x BINDINGS -> BINDINGS

(defun pat-match (pattern input &optional (bindings +no-bindings+))
  "Match pattern against input in the context of the bindings"
  (cond ((eq bindings +fail+ ) +fail+)
        ((variable-p pattern ) (match-variable pattern input bindings))
        ((eql pattern input) bindings)
        ((segment-pattern-p pattern) (segment-match pattern input bindings))
        ((and (consp pattern) (consp input))
                 (pat-match (rest pattern) (rest input)
                         (pat-match (first pattern) (first input) bindings)))
        (t   +fail+) ))
;
; segment-pattern-p: PATTERN -> bool   (if first element of PATTERN is seg-var

(defun segment-pattern-p (pattern)
  "pattern a non-empty-list, 1st element a segment-matching-pattern: ((?* var) . pat)"
  (and (consp pattern)
       (starts-with (first pattern) '?* )))

(defun match-variable (var input bindings) ; VAR x SYMBOL(-list) x BINDINGS -> BINDINGS
  "Does VAR match input? Uses (or updates) and returns bindings."
  (let ((var+val (get-binding var bindings)))
    (cond ((not var+val) (extend-bindings var input bindings))  ; add new binding
          ((equal (cdr var+val) input) bindings)                             ; do nothing
          (t +fail+ )                                                                          ; clash with existing
   )) )

; (setf b +EXAMPLE-BINDINGS+)
; (match-variable '?X '(the cat) b)
; (match-variable '?U 'dog  b)
; (match-variable '?X 'dog  b)     ; returns NIL

; segment-match: PATTERN x INPUT x BINDINGS x NAT -> BINDINGS

(defun segment-match (pattern input bindings &optional (start1 0))
"Match the pattern = ((?* var) . pat) against input - returns BINDINGS"
  (let ((var (second (first pattern)) )     ; we know ?* is the first
        (pat (rest pattern )) )
     (cond ((null pat) (match-variable var input bindings))   ; return this binding

           ;; We assume that pat, the rest of pattern, starts with a constant
           ;; In other words, a pattern can't have 2 consecutive vars
           ;; pos is index into input, the symbol matching next item in pattern
           (t (let ((pos (position (car pat) input :start start1 :test #'equalp)))
                   (if (null pos)
                         +fail+                          ; pattern-input mismatch
                         (let* ((input-rest (subseq input pos))
                                (input-prefix (subseq input 0 pos)) ; bind to var!
                                (b1 (match-variable var input-prefix bindings)) ;OK
                                (b2 (pat-match pat input-rest b1)))
                           ;; If b2 failed , try another longer one
                             (if (eq b2 +fail+)
                                  (segment-match pattern input bindings (+ pos 1) )
                                  b2) ) ) ) ) ) ) )

; (setf pattern '((?* ?W) sat on the ?V))
; (setf input '(The cat sat on sat on the mat))
; (segment-match pattern input +no-bindings+)

#| Note on segment-match (from Norvig, chapter 5.3)

In writing segment-match, the important question is how much of the input the
segment variable should match. One answer is to look at the next element of the
pattern (the one after the segment variable) and see at what position it occurs in the
input. If it doesn't occur, the total pattern can never match, and we should fail.

If it does occur, call its position pos. We will want to match the variable against the
initial part of the input, up to pos. But first we have to see if the rest of the pattern
matches the rest of the input. This is done by a recursive call to pat-match. Let the
result of this recursive call be named b2. If b2 succeeds, then we go ahead and match
the segment variable against the initial subsequence.

The tricky part is when b2 fails. We don't want to give up completely, because
it may be that if the segment variable matched a longer subsequence of the input,
then the rest of the pattern would match the rest of the input. So what we want is to
try segment-match again, but forcing it to consider a longer match for the variable.

This is done by introducing an optional parameter, start1, which is initially 0 and is
increased with each failure. Notice that this policy rules out the possibility of any
kind of variable following a segment variable.
|#

;;; --- test data for pattern matching ---

; (pat-match '(i need a ?X) '(i really need a vacation)) ; NIL
; (pat-match '(this is easy) '(this is easy))            ; ((T . T))
; (pat-match '(?X is ?X) '((2 + 2) is 4))                ; NIL
; (pat-match '(?X is ?X) '((2 + 2) is (2 + 2 )))       ; ((?X 2 + 2)) = ((?X . (2 + 2)))
; (pat-match '(?P need . ?X) '(i need a long vacation)) ;((?X A LONG VACATION) (?P . I))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; --- RULES ---
;;;
;;; Here's an example of a rule: input-matching-pattern + one or more response-patterns
;;;
;;; (  ((?* ?X) I want (?* ?Y ))                  ; Pattern part
;;;       (What would it mean if you got ?Y)      ; Three possible responses
;;;       (Why do you want ?Y)
;;;       (Suppose you got ?Y soon?)   )
;;;
;;; -----------------------------------------------------------------------------------
;;; --- ELIZA top level ---
;;;
;;; Note on output - recall (terpri) prints a newline.
;;; print is just like prin1 (or princ - human readable)
;;; except that the printed representation of object
;;; is preceded by a newline and followed by a space.
;;;
;;; pprint is just like print except that the trailing space is omitted
;;; and object is printed with the *print-pretty* flag non-nil - pretty output.

(defun eliza (rules)
  "Respond to user input using pattern matching rules. 'bye' to terminate"
  (princ "Hello, I am your doctor. Please type bye to finish.")
  (terpri)
  (terpri)
  (princ "Please type your first name then return> ")
  (setf *user-name* (car (read-line-no-punct)))              ; substitutes $name$ in response
  (loop
   (print 'speak>)
   (let ((input (read-line-no-punct)))
      (if (equalp input (list 'bye)) (progn (print 'Goodbye) (return))
          (let* ((raw-response (use-eliza-rules input rules))
                 (response (flatten1 raw-response))
                 (out  (substitute *user-name* '$name$ response :test #'equalp)) )
            (pprint out) ) ) ) )  )

; Test:  (eliza +eliza-rules+)
; Test:  (eliza +eliza-rules-extended+)

(defun read-line-no-punct ()
  "Read an input line terminated by 'return', ignore punctuation, -> symbol-list"
  (read-from-string
   (concatenate 'string "(" (substitute-if #\space #'punctuation-p (read-line))
                ")")  ))

(defun punctuation-p (char) (find char ".,;:'!?#-()\\\""))

(defun use-eliza-rules (input rules)
  "Find some rule with which to transform the input ... ."
  (some #'(lambda (rule)
            (let ((bindings (pat-match (rule-pattern rule) input)))
              (if (not (eql bindings +fail+) )
                  (sublis (switch-viewpoint bindings)
                          (random-elt (rule-responses rule )) ))))
        rules))

(defun rule-pattern (rule) (car rule))     ; The pattern to match the input

(defun rule-responses (rule) (cdr rule))   ; the list of (remaining) response-patterns

(defun switch-viewpoint (bindings)
  "Change I to you and vice versa, and so on in bindings."
  (sublis '((I . you)  (you . I)    (me . you)
            (am . are) (was . were) (are . am)) bindings ))

(defun flatten1 (l)
  "Append together elements (or lists) in the list l (not lists of lists)."
  (mappend #'mklist  l) )

(defun mklist (x)
  "Return x if it is a list, otherwise (x)."
  (if (listp x) x (list x)))

(defun mappend (fn l)   ; (* -> **) x *-list -> <flat list>
  "Apply fn to each element of list l and append the results."
  (apply #'append (mapcar fn l) ))

(defun random-elt (choices)
  "Choose an element from a list at random."
  (elt choices (random (length choices )) ))


;;; --- End ---

Tuesday, February 07, 2017

The return of (virtual) Shadow

The late Shadow

Chapter 5 of Peter Norvig's excellent "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp" is entitled "ELIZA: Dialog with a Machine". I have spent the afternoon studying his pattern-matching code and transferring it into an executable Lisp file.*

An example of an Eliza pattern is this:
'((?* ?P) need (?* ?X))
which picks up text before and after the word 'need'.

If you tell Eliza:
'(Shadow and I need a vacation),
the program will match the input with the pattern above, thus ..
(pat-match '((?* ?P) need (?* ?X)) '(Shadow and I need a vacation))
to create a binding
'((?P SHADOW AND I) (?X A VACATION))       ;   (dotted pair) binding
which can then be passed to the output-generating pattern. And so on.

---

But we're not so much interested in Eliza and that Rogerian psychoanalyst. We want Shadow, our much-missed departed cat (RIP July 1st 2016).

The first step is to change the rules: less talk of vacations and how you're feeling about your parents, more about voles. And being sick on the carpet.

The Eliza architecture was criticised, correctly, for being totally vacuous. The emptiness of the 'conversation' led to bored withdrawal after a period depending upon the narcissism of the user.

We can do better.

To add intelligence to Shadow (such a bright cat!) we have to give him knowledge (in the knowledge lies the power) together with reasoning capability.

Peter Norvig helpfully gives us an equation (chapter 16, p. 548 or thereabouts):
Expert System = Prolog + uncertainty + caching + questions + explanations
The Prolog part powers the knowledge-base capturing Shadow's deep understanding of his own likes, light-hearted escapades and more lethal habits; the Q&A allows for his more sensitive, introspective side.

Peter Norvig has a detailed chapter (11 - Logic Programming) where he explains how to implement Prolog in Lisp (interpreted).

I think this is the way to go with chatbots: combine Eliza-style interaction with a little knowledge-based reasoning to add interest and depth, and to steer the conversation. Perhaps a semantic grammar in there somewhere to help extract meaning from the user's input, though personally, given the ungrammaticality of dialogue, I've always put semantics/pragmatics first.

Anyway, watch this space. It won't be quick .. but we will bring him back!

---

* We spent the morning strolling in the sun around Cheddar reservoir.

Thursday, February 02, 2017

GPS vs ATP

There is a view to which I'm quite attracted: that an automated theorem prover is a general-purpose AI engine, which can be used to power arbitrary intelligent behaviour.



This kind of thinking goes back to the earliest days of AI. In "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp" by Peter Norvig, we read this (Chapter 4):
"The General Problem Solver, developed in 1957 by Alan Newell and Herbert Simon, embodied a grandiose vision: a single computer program that could solve any problem, given a suitable description of the problem.

GPS caused quite a stir when it was introduced, and some people in A1 felt it would sweep in a grand new era of intelligent machines. Simon went so far as to make this statement about his creation:

'It is not my aim to surprise or shock you. . . . But the simplest way I can summarize is to say that there are now in the world machines that think, that learn and create. Moreover, their ability to do these things is going to increase rapidly until - in a visible future  -the range of problems they can handle will be coextensive with the range to which the human mind has been applied.' "

GPS was not a theorem prover, it was - as the name implies - a planner. It used a logic-like syntax to express goals, initial conditions, and the preconditions and postconditions of actions. Carrying out an action, where it was applicable, would delete the preconditions from the current database and assert the postconditions.

GPS started with the goal and contemplated applying the actions in reverse, to create a tree of subgoals looking for a way back to the initial conditions.

Here is how GPS stacks blocks.


I'll come back to why GPS did not solve the problem of artificial general intelligence in a moment. Let's think about GPS and theorem proving.

Logic concerns itself with abstract relationships. It deals in a deeply uninterpreted universe of objects (constants, variables and functions), sets of those objects, and the connections between them.

It's timeless and spaceless, and if you want those things you have to explicitly introduce them, either with extra axioms or by beefing up the inference system so that you're less like a vanilla theorem prover and more like a real-world planner. This is not a small task.

Prolog exemplifies the dilemma. Prolog is a resolution theorem prover for a highly-restricted syntax of first-order logic, namely Horn clauses. But Prolog also has many built-in functions and relationships, for example arithmetic which allows time to be encoded.

It can also extra-logically alter its own axioms mid-computation.

As David H. D. Warren did in the famous WARPLAN back in 1974, you can get the functionality of an efficient planner in an enhanced theorem prover - Prolog - but it's completely non trivial.

---

So why didn't GPS take over the world?

It has a major Achilles heel. It's only as good as its operators and the expressive power of its description language. These are magically introduced by the programmer reflecting a pre-existing paradigm of problem-conceptualisation.

GPS has nothing to say about how such a paradigm might be synthesised in the first place.

This is feature (or bug) which GPS-like systems share with all rule-based systems. It's why Expert Systems proved so fragile, and hard to build and maintain.

In real life, our engagement with 'reality' is always changing, the rules never exactly apply and obsolesce even as they cohere. Learning, intervention and further understanding has to occur at a more granular level than GPS - indeed, the latter is best understood as emergent.

Although artificial neural nets, with their fluid, distributed weighting-representations are the new central dogma of AI, the GPS approach was both easier and more obvious. It even works in some stable, well-defined domains.

It had to be tried; it was hardly wasted effort.

---

Another joy from Norvig's book (available for download here) is in section 1.7: the origins of lambda notation.
"It is also possible to introduce a function without giving it a name, using the special syntax lambda. The name lambda comes from the mathematician Alonzo Church's notation for functions (Church 1941). Lisp usually prefers expressive names over terse Greek letters, but lambda is an exception. A better name would be make-function.

Lambda derives from the notation in Russell and Whitehead's Principia Mathematica, which used a caret over bound variables. Church wanted a one-dimensional string, so he moved the caret in front: ^x(x + x).

The caret looked funny with nothing below it, so Church switched to the closest thing, an uppercase lambda, Λx(x + x).

The Λ was easily confused with other symbols, so eventually the lowercase lambda was substituted: λx(x + x).

John McCarthy was a student of Church's at Princeton, so when McCarthy invented Lisp in 1958, he adopted the lambda notation. There were no Greek letters on the key punches of that era, so McCarthy used (lambda (x) (+ x x)) .. and it has survived to this day."