Showing posts with label Lisp. Show all posts
Showing posts with label Lisp. Show all posts

Monday, February 10, 2025

Pure ATPs: such a disappointment


---

I have always had a soft spot for automated theorem provers (ATPs). There is something both elegant and exciting about formalising your nontrivial problem in, say, a predicate calculus variant, then pressing the start-button and letting the machine solve it by the powers of deep deduction alone.

But ATPs have always disappointed. Doug Lenat, who spent his entire life handcrafting the general purpose intelligent system Cyc, commented at the last that they had originally encoded the facts and rules of the world in a Lisp-like formal language and then handed that knowledge base and the user-query to a powerful Resolution Theorem Prover to deduce an answer. To avoid the interminable waiting they added layer after layer of special-case heuristics. After decades of such aggregation they quietly turned off the theorem prover: it was never being used.

Edinburgh university was one of the centres of Prolog use and research in the 1980s, along with Oxford and Imperial College. Undergraduates hated it: the elegance of its specification capability was complemented by the opacity of its execution model. Debugging logic programs by mentally running a depth-first tree-search with backtracking-on-failure - well, that could tax the abstraction-powers of the keenest young minds. 

I was much happier with Lisp: you know where you are with β-reduction.

In the heady days of those applied ATPs known as Expert Systems the slogan was: “In the knowledge lies the power”; inferential capability was distinctly secondary.

The culmination of this insight was the success of the LLMs c. 2024. Enormous amounts of encoded knowledge - and no reasoning ability at all…

And yet, there are still those of us who value the elegance of inference... and now, in 2025, my happiness is complete: those LLMs can now reason!


Sunday, November 05, 2017

Towards the esoterically-programmed chatbot

Gary Larson has this famous cartoon:



It might as well be labelled, 'What chatbots hear'.

I type something profound to the chatbot, and this is what the program gets:
"I     *!@      +^%    £")#     owl      +=&£."
Plainly no amount of inference is going to reconstruct that. However, a gossipy chatbot has only to keep the conversation going .. .



An Eliza-type program uses patterns such as:
"I tokens* owl tokens*"  => "How interested are you in owls?"
where the response is bland enough to match most owl-related utterances.

If the chatbot can recognise a little more, perhaps put some syntactic structure to it, then we could do a semantically-informed best match to the noisy user input using a metric over the space of semantic structures (I'm thinking something like situation semantics, or more likely an extensible, data-populated semantic net).

It might be tempting to map everything into a vector space but that's way too much gratuitous (and irrelevant) structure: like doing logic programming using arithmetic over Gödel numbering. To save us from that was why God invented compilers.

---

I'd like to play with some of these ideas, restart my stalled chatbot programme. But I'm lazy, I don't want to do low-level coding, I want a really high-level language which lets me get straight into the problem space. And this brings me - via consideration of Lisp and Haskell - back to Prolog.

As I wrote a couple of years ago,
"First, Prolog. Its supporters always touted it as a higher-level language than Lisp - though I always found Lisp more congenial, I like to set up data structures and manipulate them explicitly. With Prolog you define relationships between things and the miraculous powers of unification and depth-first search with backtracking pull magical rabbits out of hats. The Eliza program in Prolog can be read in its entirety on one screen, ditto for the blocks world planning system.

This procedural power is the result of enormously complex recursive structures built at execution time by the Prolog system. It frequently defies one's powers of abstraction, short-term memory and inference to visualise what's actually going on. I know you're meant to read and understand the programs declaratively, but in reality you don't get too far without a consideration of what actually happens at run-time.

Still, the power to write ridiculously-powerful programs in just a few lines of code is addictive. It reminds me of the first time I fired the General-Purpose Machine Gun (GPMG). I was good with the Lee-Enfield rifle and prided myself on my accuracy; the GPMG just bounced around and hosed the target. So much power and so little control!"
---

Oh, and here's Eliza in Prolog (as modified to represent our deceased pet, Shadow) from the Sterling and Shapiro book, 'The Art of Prolog', (chapter 14):
shadow :-
write('Hello, I am Shadow. Miaow!'),
nl,write('Please type your thoughts and press return.'),
nl,write('To finish type bye'),nl,
read_word_list(Input),shadow(Input),!.

shadow([bye]) :- reply(['Goodbye, miaow!']).

shadow(Input) :-
pattern(Stimulus,Response),
match(Stimulus,Dictionary,Input),
match(Response,Dictionary,Output),
reply(Output),
read_word_list(Input1),
!,shadow(Input1).

match([Word|Pattern],Dictionary,[Word|Target]) :-
atom(Word),
match(Pattern,Dictionary,Target).

match([N|Pattern],Dictionary,Target) :-
integer(N),
append(LeftTarget,RightTarget,Target),
lookup(N,Dictionary,LeftTarget),
match(Pattern,Dictionary,RightTarget).

match([],_,[]).


reply([Head|Tail]) :- write(Head), write(' '),reply(Tail).

reply([]) :- nl.

lookup(Key,[(Key,Value)|_],Value).

lookup(Key,[(Key1,_)|Dict],Value) :- Key \= Key1,lookup(Key,Dict,Value).

There are some lower-level functions (and the relevant patterns) defined elsewhere, but this is the gist of it. Pretty clear, wouldn't you say?


Amazon link

I used to think it was just me, but I read somewhere of the despair of computer science students at Edinburgh university at the sheer intellectual difficulty of writing (and even understanding) non-trivial programs in Prolog. It would seem there's a high IQ-cutoff just to use the language at all.

This reminds me of Marain, the language of the Culture, where those dialects used by the Minds were simply beyond the intellectual capacities of humans. And while we're on that case, let me remind you of a real-world counterpart: Malbolge.
"... invented by Ben Olmstead in 1998 and named after the eighth circle of hell in Dante's Inferno. "Malbolge was specifically designed to be almost impossible to use, via a counter-intuitive 'crazy operation', base-three arithmetic, and self-altering code." *

In fact the author of Malbolge was unable himself to write a program in it.

In the end it required an AI system to write the first program, using a form of 'best-first' search in the space of all possible programs.

Here is the "Hello World!" program in Malbolge.
(=<`#9]~6ZY32Vx/4Rs+0No-&Jk)"Fh}|Bcy?`=*z]Kw%oG4UUS0/@-ejc(:'8dc
---

* Malbolge design trivia.
After each instruction is executed, the guilty instruction gets encrypted so that it won't do the same thing next time, unless a jump just happened. Right after a jump, Malbolge will encrypt the innocent instruction just prior to the one it jumped to instead."
Of course, with artificial neural networks and deep learning, we're already away with the fairies as far as esoteric programming is concerned.

As for me, I've re-installed SWI-Prolog. Time to get up to speed with programming in logic again - so hard to think with, yet so much more compact than Lisp.

Friday, March 03, 2017

Diary: programming is hard!

I remember a post by James Thompson (can't find it - sorry) describing the joy of giving IQ tests to bright students. Their smug condescension as they breeze through the early items; their horror as they hit their cognitive limits and start to sweat: "Wait a mo, .., just can't seem to see it ... ."

In artificial intelligence textbooks it's standard to cover the coding of theorem provers for propositional-calculus. Hidden away in the advanced exercises is the suggestion to extend the program to cover the full predicate-calculus. Inevitably, this is flagged as hard.

Tell me about it. Today I got basic binary resolution to work. Great! I can do inference. And yet this is not the central mystery of a predicate-calculus resolution theorem prover (RTP).

The conceptual problems arise from the layers of abstraction around the proof procedure. At the risk of boring you even further, binary resolution is driven by the unification of complementary literals (basic formulae). These two literals occur in the two clauses offered to the resolution function (hence binary resolution).

A  problem addressed by an RTP comprises: assumptions  = the axioms, a set of clauses, plus the problem itself, a goal clause.

Here's my working example. First come the axiom clauses:
(defvar *c3*   (mk-fact-clause '(likes rod horvath)))
(defvar *c4*   (mk-fact-clause '(likes sally renner)))
(defvar *c5*   (mk-fact-clause '(likes sally rod)))
(defvar *c6*   (mk-fact-clause '(likes hardy renner)))
(defvar *c7*   (mk-fact-clause '(likes hardy rod)))
(defvar *c8*   (mk-fact-clause '(amusing hardy)))
(defvar *c9*   (mk-fact-clause '(likes horvath moties)))
(defvar *c10* (mk-rule-clause '(likes sally ?x) '((likes ?x moties)) ) )
(defvar *c11* (mk-rule-clause '(likes rod ?x) '((likes ?x renner) (likes ?x rod)) ) )
(defvar *c12* (mk-rule-clause '(likes ?x ?y) '((amusing ?y) (likes rod ?y)) ) )
(defvar *c13* (mk-fact-clause '(likes ?x ?x)))

(defvar *g1* (mk-goal-clause '((likes sally ?who)) ) )  ; this is the problem clause
You may notice a "Mote in God's Eye" theme here.

Despite the simplicity of these facts and rules, you'll struggle a bit to figure out the complete list of who, exactly, Sally Fowler likes.

I expect better from my program - once completed.

---

So a clause might look like this (which you will recognise as a Prolog-style Horn-clause):
'( (likes sally ?x) ← ((likes ?x ?y) (likes ?y moties)) )   ; a rule clause
which is already a bit complicated.

Then we have to set up structures for the knowledge-base (facts and rules), the goals which emerge from the resolution process, and the pointers and bindings which allow a reconstruction of proofs.

---

In telling you this, my intention is not to document the program, my point is more psychological.

You need to keep a very great deal of abstract structure in your head simultaneously if you hope to put this not-entirely-trivial program together. Plus lots of functions.

It's very g-loaded, much like doing mathematics.
"It's quite hard getting figures but ... it appears that the average IQ of students applying for PhD programmes at good universities in computer science is around 128.

"That sounds right to me. Most software development companies don't take people without good first degrees or a higher degree in a STEM subject - and that's just the pool we're talking about here."
---

Parenthetically, thank God for Lisp, a gift from the deity for clear, conceptual, exploratory thinking.

---

I read endless texts in the media from innumerate journalists about how unemployed or newly-redundant workers are going to retrain as software developers. Those writers couldn't hack it themselves and sadly, neither will most of those no-longer-required workers.
"Wait a mo, ..., just can't seem to see it ... ."
At an IQ threshold of 128, we're talking about 2.5% of a population normed at 100.

A caveat. It's intellectually hard writing machine learning programs or configuring recalcitrant artificial neural nets on novel problem-domains .. or programming RTPs. Yet for everyone doing those things, there are ten people paid to use graphical web design tools or load databases, or do a bit of scripting. Things which are not that hard.

Like many occupations, there has been mission-creep in the definition of software developer.

---

And why am I making such heavy weather of this wretched theorem-prover? This.

Saturday, February 18, 2017

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?"

Thursday, February 09, 2017

Diary: weights + Lisp reader issues + trim & style

Consider a hulking biker, tattoos and leotard, bench-pressing some massive barbell.

Alongside him, place that irritatingly-cheerful hunk Dr Chris van Tulleken, raising and lowering some wimpy baby dumbbells.

Pretending to be exhausted. Not this stagey picture below.



It was all in aid of this study (in the latest series of "Trust Me, I'm a Doctor").
"The study split 49 weight trainers into two groups and started them on a 12-week weight training programme. For each participant, they calculated their ‘one-repetition maximum’ or 1RM – that’s the heaviest weight they can lift.

"They then split the study into two groups, one group lifting 30-50% of their 1RM and the other group lifting 75-90%. The key thing was that each group lifted their weights to ‘volitional failure’ – in other words, they lifted until they couldn’t lift any more.

‘Failure’ will happen to anyone and everyone, however strong, if they do enough repetitions. So the group lifting the lighter weights did a larger number of reps (20-25) than the group lifting the heavier weight (8-12).

"The theory behind muscle failure is to do with ‘motor units.’ Motor units are bundles of muscle fibres controlled by a nerve. When you lift a weight, motor units will be required to contract the muscle. With each lift, some motor units will get fatigued, so additional motor units need to be used to do the next lift. Sooner or later you get to a point where all your available motor units have been exhausted – that’s what causes your muscles to fail.

"In the McMaster study, the results showed that despite lifting different weights, both groups showed the same increase in strength and muscle growth. In other words, doing heavy weights with fewer reps or lighter weights with more reps made no difference. These results agreed with earlier research conducted by the same group.

"So what does that mean for the rest of us? Well, it means that you can get results lifting heavy weights OR lighter weights, so long as you’re pushing your muscles to work harder than they normally do. You don’t always need to lift to failure to get results – but your muscles need to be ‘overloaded’ compared to your normal day to day life. Strength and conditioning coach Richard Blagrove from St. Mary’s University, Twickenham, suggests that on a scale of 1 to 10, where 10 is repetition failure, lifting to 7 or 8 is about right.

"If your muscles are feeling that overload once a week, your body will adapt and get stronger. If you want to continue to get stronger, you will need to constantly re-assess and progress your weight or rep level, to make sure you are always pushing your muscles beyond their comfort zone. If your weight training feels easy, it probably isn’t doing anything for you.

"You can get results using weights machines or free weights. Free weights also force you to use stabiliser muscles meaning you use more energy, and your joints move in their most natural way. But it’s important to lift correctly, so as soon as your “form” starts to go, you should probably stop. If you DO want to push yourself to failure, weight machines might be the safest place to do it. If you lift to failure with free-weights you need a partner who can relieve you of the weight when you can no longer lift it."
In a nutshell, don't go with "go heavy or go home!".

Do enough reps so that the last three are 'difficult'. Obviously you need enough weight so that you can get there within, say, 8-15 reps.

---

While I was watching our recording of "Trust Me, ..." my subconscious was whirring furiously. This afternoon I had painstakingly edited 43 rules for my Eliza program, which I'm reconstructing. The program works! But the rule set:
(defparameter +eliza-rules-extended+  '(.. stuff .. ))
refused to compile: weird and incomprehensible error messages complaining of 'invalid traits'. We're meant to be AI-advancing daily, but our development environments haven't the first clue.

My epiphany was that a rule which said something like:
(Why don't you like your mother?)
is going to hit a major problem with that quote character.

I rushed upstairs and deleted all the quotes from don't, doesn't, it's .. and everything loaded properly. Tomorrow I'll test it thoroughly and maybe post the code.

That should thrill you, dear reader.

---

As you know, my first target emulation is going to be the cat. Clare, who had to suffer through a tedious explanation of my afternoon difficulties, suggested that I should be designing a chatbot for the elderly. I'm to data-fill it with small talk about family, friends and neighbours (and pets?).

I suspect there's a market for that, and I'm not completely convinced that a state-of-the-art artificial neural net is required to implement it either.

But here to the contrary is Google's view:
"A simple strategy to build lightweight conversational models might be to create a small dictionary of common rules (input → reply mappings) on the device and use a naive look-up strategy at inference time.

This can work for simple prediction tasks involving a small set of classes using a handful of features (such as binary sentiment classification from text, e.g. “I love this movie” conveys a positive sentiment whereas the sentence “The acting was horrible” is negative).

But, it does not scale to complex natural language tasks involving rich vocabularies and the wide language variability observed in chat messages."
---

The diary would not be complete without observing that Clare had her hair done today.


I did notice.

Saturday, January 14, 2017

The long road to noughts and crosses

Clare innocently asks why, after five afternoons of programming, we still don't have a program which can play noughts and crosses.

The game seems pretty trivial. Just arrange for the program to play in the corners, then complete 'three in a row' if it can. Probably the system will never lose and will win quite often.

Yes, I could have done that.

---

I explain that in the version I'm working on, the computer starts with no information about noughts and crosses and no built-in ideas about how to play.

Faced with a blank board there are nine possible places to put its first 'X'. It has no reason to prioritise one over another, so it therefore generates nine possible board positions.

For each of these, it doesn't know where its opponent will place its first 'O', so that's eight possibilities it has to consider. It's now juggling a tree of depth two with 72 options.



The process repeats. No win or loss can occur until the fifth move (3 'X's and 2 'O's) by which time the tree has branched to 15,120 possible boards. Most positions are still in-play though.

Lacking a priori insight, the program has to apply a combination of things. Looking ahead, say, to depth 5, it can score future boards where it wins very positively, and positions where it loses very negatively. Ongoing positions it has to judge more heuristically, creating a 'how good is this for me?' score.

Then it has to somehow back-up these terminal scores which are maybe five or more moves out, bringing them back so that they give guidance for the very next move.

Effectively, the computer is asking itself: what next move maximises my chances to being on a road which ends up with a win, despite my opponent trying to thwart me on every turn?

This is the famous 'minimax' algorithm.

So plenty of apparatus to put together before the first cross gets entered in the first game.

I'm almost there.

---

Once the apparatus of tree generate-and-test has been written and debugged, it can easily be extended to interactions which are less trivial than noughts and crosses.

Automated Theorem Provers and Expert Systems also build trees and evaluate nodes against success criteria. The difference is that the trees they build are not adversarial, so no minimax.

But a conversation planning system is more like a two-player game.

My goal of a smarter chatbot with inference and conversational direction is still very firmly in my mind .. although it's a way off.

Thursday, December 22, 2016

J. A. Robinson's Lisp code for his resolution theorem prover

Here are the pages - from Chapter 13 of "Logic: Form and Function" - where J. A. Robinson documents and describes his hyper-resolution theorem prover in Lisp. You will find the Lisp interestingly archaic.

My apologies for the poor quality - it was done in a rush. Nevertheless, the material is quite readable. It's published as the PDF link below.

PDF


Monday, December 19, 2016

Matlda: the gatekeeper to your new job - Not!

From the Financial Times last month.

Matlda the robot and Professor Khosla

"She specialises in interviewing candidates for sales positions. Although relatively new to the job, Matlda still knows more than those she grills and uses her arsenal of 76 questions with ruthless efficiency to assess a job hopeful’s skills and professional expertise.

"She starts her 25-minute sessions slowly, reading her interviewee’s emotions and putting them at ease by, for example, playing the music she knows they listen to at home.

Matlda is a 30cm tall robot designed to shortlist job applicants and interview them.

...

“When you are doing face to face interviews and you have 10 candidates, if you liked candidate number four, by the time candidate number seven arrives the decision is already made unless they are something exceptional,” says Prof Khosla. “Matlda gives candidates a fair go.”

" .. a robotic interviewer “monitors [the candidate’s] facial expression”, says Prof Khosla. “Is there any physiological response? Do they seem impassioned when they are relating their experience? That is very important information [to glean from] a face to face interview — it tells an interviewer they relate more intrinsically to that area.”

"The robot compares what it has learnt with the traits of successful employees at the company that is doing the hiring. This is particularly helpful in sales, where turnover is high. “It’s all based on how the emotional responses and cognitive responses benchmark against their most successful candidates in their own culture,” says Prof Khosla."
It seems to work, at least with some people.
"Yu Ang Tan, a software engineer who engaged in a trial interview with Matlda, found the process uplifting. “I feel that a Matlda-enabled interview process gives me the feeling of a more standardised interview process.

“At the same time, having the process conducted by a robot with a cute appearance encouraged me to open up to it in ways I would otherwise hold back with a human interviewer.”
---

This is so obviously a gimmick that I wouldn't normally have wasted your time with the piece. But job interviews have some salience in our household at the moment.

Alex has a panel after Christmas and is currently prepping by studying Scala, a souped-up descendant of Java that I hadn't heard of before. He has bought the 800 page book.

Flipping through it, I exclaimed: "This is basically Lisp!", thus restating Greenspun's Tenth Rule.

Amazon link

With Scala's polymorphic typing and higher-order functions, I found myself this morning having a conversation I would never have anticipated: lambda calculus and currying.

Friday, December 16, 2016

DVD challenge, LispWorks, Bark Chippings and Weeds

Our DVDs

DVDs on the left belong to one of us; those on the right to the other. Your (not very difficult) challenge is to decide which are Clare's and which are mine, and where the boundary is.

Click on image to make larger if you can summon up the energy.*

---

Downloaded LispWorks Personal Edition this morning. I've been put off in the past by the unfriendly tone of the Ts&Cs:
"Please note that the LispWorks Personal Edition, distributed free of charge, has the following intentional limitations:

  • There is a heap size limit which, if exceeded, causes the image to exit. A warning is provided when the limit is approached.

  • There is a time limit of 5 hours for each session, after which LispWorks Personal exits, possibly without saving your work or performing cleanups such as removing temporary files. You are warned after 4 hours of use.

  • The functions save-image, deliver, and load-all-patches are not available.

  • Initialization files are not loaded.

  • Layered products that are part of LispWorks Professional and Enterprise Editions (CLIM, KnowledgeWorks, Common SQL and LispWorks ORB) are not included."
But it's well-supported and they have to make money. As with all language/development systems there's that steep initial learning curve. This afternoon it's PDF manual time - if I can summon up the energy.

---

In other news, I'm expecting two tons of bark chippings for the front garden to be delivered this afternoon. To be spread on the anti-weed mats Clare already laid out.




I'm also expecting Clare herself at some point, bearing the Christmas wreath she's meant to have learned how to make at the Bishop's Palace lunchtime class (just finished at time of writing), plus the prizes she won at the Labour Party Christmas raffle last Saturday in Wells Town Hall which need picking up on the Glastonbury Road: a bit of a stroll from the Palace.

"If they're too heavy, give me a ring," I said. "I'll pick you up in the car."

That would be the car which I won't be able to get out of the drive on account of two enormous bags of bark chippings blocking the bottom.


Later: my fears prove groundless as the first bag is placed carefully on the mat
---

* Yep, I'm just the SF (and GoT). All the rest are hers.

Wednesday, December 14, 2016

Winston & Horn: A Propositional Calculus Resolution Theorem Prover in Lisp

From by Patrick Winston's and Berthold Horn's famous classic on AI and Lisp (1981) - the first edition is available as a PDF here.

Amazon link:(3rd edition)


How to code a resolution theorem prover for the propositional calculus in Lisp (page 232).

---

Resolution is one way to Prove Theorems In Propositional Calculus 

Theorem Proving is a highly developed field that requires considerable mathematical sophistication to understand fully. Still, if we limit ourselves to proofs in the propositional calculus, we can build a simple theorem prover. It will be based on the so-called resolution principle (which can be extended to deal with the more difficult problems of the predicate calculus). The key to this theorem prover, again, is a matcher.

A theorem in the propositional calculus, for our purpose, consists of a premise and a conclusion, both expressed in LISP-like prefix notation. The following sets up a typical premise and conclusion:

(SETQ PREMISE
   '(AND (OR Q (NOT P))
               (OR R (NOT Q))
               (OR S (NOT R))
               (OR (NOT U) (NOT S))))

(SETQ CONCLUSION
   '(AND (OR (NOT P) (NOT U))))

These are examples of conjunctive normal form since only atoms appear inside NOTs, only NOTs or atoms appear inside ORs, and only ORs appear inside ANDs. Each of the OR lists is called a clause. Each atom or atom with a NOT is called a literal.

Our theorem prover will use the assumption that all inputs are in conjunctive normal form because it can be shown that anything written in terms of ANDs, ORs, and NOTs can be placed in equivalent conjunctive normal form.

■ To prove a theorem, it must be shown that the premise implies the conclusion. For a premise to imply a conclusion, it must be that any combination of T and NIL values for the atoms in the premise that make the premise evaluate to T also makes the conclusion evaluate to T. Or said another way, to prove a theorem, it must be shown that any combination of literal values that makes the premise true also makes the conclusion true.

Clearly, theorems can be proved by simply trying all ways to bind the atoms to T and NIL, checking that no combination causes the premise to evaluate to T and the conclusion to NIL. Resolution offers an alternative. We first list the steps involved to give a general feel for what is involved, and then we will explain why they work.

■ Step 1: Negate the conclusion, put it into conjunctive normal form, and combine it with the premise.

In our example, negating the conclusion yields the following:

(AND (OR P) (OR U))

Combining this with the premise produces the following result:

(AND (OR P)
           (OR U)
           (OR Q (NOT P))
           (OR R (NOT Q))
           (OR S (NOT R))
           (OR (NOT U) (NOT S)))

■ Step 2: Search for two clauses in which the same atom appears naked in one and negated in the other. Form a new clause by combining everything in the two clauses except for the naked atom and its negation. The two clauses involved are said to resolve. The new clause is called a resolvent. Combine the resolvent with the other clauses.

For the example, the first and the third clauses resolve, producing a resolvent. That is, (OR P) and (OR Q (NOT P)) yield (OR Q). Combining this with the rest of the clauses yields this:

(AND (OR Q)
           (OR P)
           (OR U)
           (OR Q (NOT P))
           (OR R (NOT Q))
           (OR S (NOT R))
           (OR (NOT U) (NOT S)))

■ Step 3: Repeat step 2 until no two clauses resolve or two clauses resolve to (OR). If no two clauses resolve, report failure. If two resolve to (OR), report success.

The key step clearly is a matching process, the one that produces resolvents of two clauses. The following matching function does the job: 

(DEFUN RESOLVE (X Y)
    (PROG (REST-X REST-Y)
        (SETQ REST-Y (CDR Y))         ; Get rid of OR.
        (SETQ REST-X (CDR X))         ; Get rid of OR.
        LOOP
        (COND ((NULL REST-X) (RETURN 'NO-RESOLVENT))      ; Any atom left to try?
                     ((MEMBER ( INVERT (CAR REST-X)) REST-Y)        ; Is negation in Y?
                      (RETURN (CONS 'OR                                                   ; Add OR.
                                                     (COMBINE (CAR REST-X)           ; Tidy up.
                                                                          (APPEND (CDR X) (CDR Y)))))))
         (SETQ REST-X (CDR REST-X))
        (GO LOOP))) 


Note that two auxiliary functions are needed. INVERT returns a bare atom if the argument is in the form of (NOT <atom>) . It wraps its argument in a NOT if the argument is an atom. COMBINE gets rid of the match-causing atom and its negation and makes sure there are no repeated elements in the resulting clause:

(DEFUN INVERT (X)
               (COND ((ATOM X) (LIST 'NOT X))
                             (T (CADR X)))) 


(DEFUN COMBINE (A L)
               (COND ((NULL L) NIL)
                             ((OR (EQUAL A (CAR L))                                     ; Is it there?
                                      (EQUAL (INVERT A) (CAR L))                   ;  Is negation there?
                                      (MEMBER (CAR L) (CDR L)))                     ; Is it there twice?
                              (COMBINE A (CDR L)))                                       ; Then get rid of it.
                            (T (CONS (CAR L) (COMBINE A (CDR L))))))    ; Otherwise keep it.

The function PROVE consists of nested loops that search for resolvable clauses and add resolvents to the clause list. Here we show it applied to an example: 

(PROVE PREMISE NEGATION)
    (THE CLAUSE (OR Q (NOT P)))
    (AND THE CLAUSE (OR R (NOT Q)))
    (PRODUCE A RESOLVENT: (OR (NOT P) R))
    (THE CLAUSE (OR (NOT P) R))
    (AND THE CLAUSE (OR S (NOT R)))
    (PRODUCE A RESOLVENT: (OR (NOT P) S))
    (THE CLAUSE (OR (NOT P) S))
    (AND THE CLAUSE (OR (NOT U) (NOT S)))
    (PRODUCE A RESOLVENT: (OR (NOT P) (NOT U)))
    (THE CLAUSE (OR (NOT P) (NOT U)))
    (AND THE CLAUSE (OR P))
    (PRODUCE A RESOLVENT: (OR (NOT U)))
    (THE CLAUSE (OR (NOT U)))
    (AND THE CLAUSE (OR U))
    (PRODUCE THE EMPTY RESOLVENT)
    (THEOREM PROVED)

There are, incidentally, many ways to make resolution more efficient by limiting the attempts at resolving clauses. For example, any clause containing an atom and its negation can be ignored. 

(DEFUN PROVE (PREMISE NEGATION)
     (PROG (FIRST REST REMAINDER RESOLVENT CLAUSES)
          (SETQ CLAUSES (APPEND (CDR PREMISE)           ; Purge ANDS
                                                           (CDR NEGATION)))
          FIND-CLAUSE                                                       ; this is a label for 'GO' at end
          (SETQ REMAINDER CLAUSES)
         TRY-NEXT-X-CLAUSE
          (COND ((NULL REMAINDER) (RETURN '(THEOREM NOT PROVED))))
          (SETQ FIRST (CAR REMAINDER))
          (SETQ REST (CDR REMAINDER))
        TRY-NEXT-Y-CLAUSE
         (COND ((NULL REST) (SETQ REMAINDER (CDR REMAINDER))  ; Doesn't resolve.
                                                (GO TRY-NEXT-X-CLAUSE)))
         (SETQ RESOLVENT (RESOLVE FIRST (CAR REST)))                   ; Try resolving.
         (COND ((OR (EQUAL RESOLVENT 'NO-RESOLVENT)
                               (MEMBER RESOLVENT CLAUSES))                          ; Resolvent known.
                        (SETQ REST (CDR REST))
                        (GO TRY-NEXT-Y-CLAUSE))
                       ((NULL (CDR RESOLVENT))                                                ; Resolvent empty.
                        (PRINT (APPEND '(THE CLAUSE) (LIST FIRST)))
                        (PRINT (APPEND '(AND THE CLAUSE) (LIST (CAR REST))))
                        (PRINT '(PRODUCE THE EMPTY RESOLVENT))
                        (RETURN '(THEOREM PROVED)))
                      (T (SETQ CLAUSES (CONS RESOLVENT CLAUSES))         ; Resolvent is new.
                       (PRINT (APPEND '(THE CLAUSE) (LIST FIRST)))
                       (PRINT (APPEND '(AND THE CLAUSE) (LIST (CAR REST))))
                       (PRINT (APPEND '(PRODUCE A RESOLVENT:) (LIST RESOLVENT)))
                       (GO FIND-CLAUSE))))) 

---

I haven't yet tried to copy and paste this code into a Lisp system so there may be the odd parenthesis missing. After checking it out, my next step would be to remove all those confusing loops and write it in a recursive fashion. Also experiment with different control strategies, such as set-of-support.

But Heidi Morkland was way ahead of me.

I do find the archaic style rather attractive (CADR!).

---

Compare this PL resolution prover written in Prolog by Markus Triska in 2006.
Resolution calculus for propositional logic.

   Input is a formula in conjunctive normal form, represented as a
   list of clauses; clauses are lists of atoms and terms not/1.

   Example:

   ?- Clauses = [[p,not(q)], [not(p),not(s)], [s,not(q)], [q]],
      pl_resolution(Clauses, Rs),
      maplist(writeln, Rs).
   %@ [p,not(q)]-[not(p),not(s)]-->[not(q),not(s)]
   %@ [s,not(q)]-[not(q),not(s)]-->[not(q)]
   %@ [q]-[not(q)]-->[]

   Iterative deepening is used to find a shortest refutation.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */


pl_resolution(Clauses0, Chain) :-
        maplist(sort, Clauses0, Clauses), % remove duplicates
        length(Chain, _),
        pl_derive_empty_clause(Chain, Clauses).

pl_derive_empty_clause([], Clauses) :-
        member([], Clauses).
pl_derive_empty_clause([C|Cs], Clauses) :-
        pl_resolvent(C, Clauses, Rs),
        pl_derive_empty_clause(Cs, [Rs|Clauses]).

pl_resolvent((As0-Bs0) --> Rs, Clauses, Rs) :-
        member(As0, Clauses),
        member(Bs0, Clauses),
        select(Q, As0, As),
        select(not(Q), Bs0, Bs),
        append(As, Bs, Rs0),
        sort(Rs0, Rs), % remove duplicates
        maplist(dif(Rs), Clauses).
This may be a lot shorter but (as is often the case with Prolog programs) its operation is fairly opaque to me. In Lisp you see what you're doing; in Prolog you have to imagine execution through a complex, sprawling and invisible search tree.

I prefer Lisp.

---

And here's a resolution prover for the propositional calculus in Python.

Like I said, I prefer Lisp.

Tuesday, May 12, 2015

Prolog

I was a terrible teacher. All my interest was in teaching those secondary-modern kids maths. This was not, however, their interest; they needed a lion-tamer, not an intellectual. After my Head of Department's nervous breakdown I headed off. The Civil Service seemed uninterested in hiring a member of the International Marxist Group; KBS Computer Services was less picky and so I became a COBOL programmer.

They say COBOL damages the brain - but I speak as a survivor. After some years of commercial programming I made my escape into a research environment (STL) and programmed in the world's best language, LISP.

Alex is a Java developer and has been doing an assessment of various programming and scripting languages. He treats LISP with the utmost disdain, a response I consider unfathomable. To mention the lambda calculus would go right over his head - 'how many transactions per second?' would be his mindset.

I am thinking of playing around with Prolog. Its power and economy are legendary, and there's a neat online guide to writing expert systems in the language. In the past I struggled to conceptualise its depth-first, backtracking execution model. With LISP I could generally figure out what a succinct program was going to do; with Prolog, not so much. But this could change - there is a powerful free system, SWI Prolog to play with.

I have ordered a book which I will use to torment Alex. Sheer professional pride will surely force him to master the unification algorithm and resolution refutation in Horn clauses before the inevitable rejection of the language*.

---

* I don't mind the technical nitpicking - execution speed and memory management, etc; it's the moral disapproval - like 'what kind of idiot would you have to be to prefer this to Java?'

Thursday, August 08, 2013

Object-Oriented Programming

I remember when Smalltalk first came out, with its new programming paradigm. I even took a course (in Watford! ) but never used it for real. After  narrowly avoiding brain damage through use of COBOL at the start of my programming career, I was actually paid to write code in ML and Lisp - elegant functional programs which used recursion, had functions as first-class values and eschewed side-effects in favour of returning values.

I am finding it hard to get my head around OOP in Python. I keep expecting methods to return values (let's say I have a strong ethical bias that they should! ) but it seems we're mostly about changing the values of instance variables by side effect or assignment. I struggle to suppress nausea.

My attempts to rewrite my simple resolution theorem prover in an object-oriented style have foundered under such continuing mis-expectations: after two hours I've just managed to get the 'clause' class with its methods defined correctly. Many minutes were spent staring at the screen in plain bafflement.  Why is it doing that???

However,  I do buy into the superior modularity and encapsulation so will persist with objects till they come naturally!