
<rss version="2.0">
  <channel>
    <title>Fu bared</title>
    <link>http://www.jalat.com/blogs/lisp</link>
    <description>Newbie excursions in  lisp</description>
    <language>en</language>
    <item>
      <title>Parsing logs</title>
      <link>http://www.jalat.com/blogs/lisp?id=5</link>
      <pubDate>Fri, 4 Feb 2006 13:02:09 GMT</pubDate>
      <description>&lt;p&gt;

So I made a blog and some requests have started coming in. And of
course I want to get some data about my visitors.

&lt;/p&gt;
&lt;p&gt;

I could just download a program from somewhere and get all the
statistics I could think of in less than ten minutes, but where is the
fun in that?  Better to spend hours to try to write some lisp code
that barely manages to get the most basic stats from the logfiles.

&lt;/p&gt;
&lt;p&gt;

You&#039;ll notice that I redefine the same function again and again and
again. This is how I usually work. Gradually refining functions until
I think they work as I want.(This is where you&#039;re appaled by the lack
of unit testing/formal verification. I basically fiddle until it works
for the limited amount of test cases I have.)

&lt;/p&gt;
&lt;p&gt;

First some libraries. I&#039;m gonna chicken out of the hard work of the
parsing because &lt;a href=&quot;http://weitz.de/&quot;&gt;Edi Weitz&lt;/a&gt; already did
that and made the &lt;a href=&quot;http://weitz.de/cl-ppcre/&quot;&gt;cl-ppcre&lt;/a&gt;
package which implements perls regular expressions in Common Lisp.

&lt;/p&gt;
&lt;pre&gt;

(defpackage :com.jalat.logparse
  (:use :cl :cl-ppcre))

&lt;/pre&gt;
&lt;p&gt;

A short run-down of the regular expressions I&#039;m going to use for those
who don&#039;t know perl regular expressions:

&lt;/p&gt;
&lt;table&gt;
  &lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt; most characters matches themselves.&lt;/td&gt; &lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;\S&lt;/td&gt;&lt;td&gt;matches non-empty characters (anything but spaces, newlines and tabs).&lt;td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;\d&lt;/td&gt;&lt;td&gt;matches digits.&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;\w&lt;/td&gt;&lt;td&gt; matches alphanumeric characters (Uses &lt;code&gt;alphanumericp&lt;/code&gt;, 
	                                   might differ from implementation to implementation).&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;[abc]&lt;/td&gt;&lt;td&gt;matches a list of characters.&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;[^abc]&lt;/td&gt;&lt;td&gt;matches everything except the list of characters.&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;(pattern)&lt;/td&gt;&lt;td&gt;stores pattern in a &quot;register&quot; for later use&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;+&lt;/td&gt;&lt;td&gt;repeat previous character/group one or more times&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;*&lt;/td&gt;&lt;td&gt;repeat previous character/group zero or more times&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;{n}&lt;/td&gt;&lt;td&gt;repeat previous character/group n times&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;|&lt;/td&gt;&lt;td&gt;means or, so (a|b) matches a or b. &lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;^&lt;/td&gt;&lt;td&gt;at the start of line, means the beginning of a line so &quot;^a&quot; does not match &quot;ba&quot;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;

Here&#039;s two log entries, this is actually one request.
The first request use a old url, and I redirect the visitor to the new
url. (Which by now also is an old url... If only planning things were
fun I might actually start doing some one day.):

&lt;/p&gt; 
&lt;pre&gt;

222.153.17.71 - - [08/Jan/2006:00:14:47 +0000] &quot;GET /back-of-the-envelope.html HTTP/1.1&quot; 302 302 &quot;http://planet.lisp.org/&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.2&quot; &quot;-&quot;
222.153.17.71 - - [08/Jan/2006:00:14:48 +0000] &quot;GET /blog.ucw?entry-id=2 HTTP/1.1&quot; 200 15016 &quot;http://planet.lisp.org/&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.2&quot; &quot;-&quot;

&lt;/pre&gt;
&lt;p&gt;

The first part is the ip address of the user who looked at our blog.
As a simple demo of how to use cl-ppcre, I&#039;ll scan and collect the
first string up until the first whitespace. (hopefully gathering
the ip address in the process.) The &lt;code&gt;register-groups-bind&lt;/code&gt;
will do the scanning and storing (binding) for me.

&lt;/p&gt;
&lt;pre&gt;

(in-package :com.jalat.logparse)

(defparameter *teststrings* &#039;(&quot;222.153.17.71 - - [08/Jan/2006:00:14:48 +0000] \&quot;GET /blog.ucw?entry-id=2 HTTP/1.1\&quot; 200 15016 \&quot;http://planet.lisp.org/\&quot; \&quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.2\&quot; \&quot;-\&quot;&quot; 
                              &quot;222.153.17.71 - - [08/Jan/2006:00:14:47 +0000] \&quot;GET /back-of-the-envelope.html HTTP/1.1\&quot; 302 302 \&quot;http://planet.lisp.org/\&quot; \&quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.2\&quot; \&quot;-\&quot;&quot;))

(defun split-string (logstring)
    (register-groups-bind 
      (ipaddr) 
      (&quot;(\\S+) &quot; logstring)
    (list ipaddr)))

COM.JALAT.LOGPARSE 39 &gt; (first *teststrings*)
&quot;222.153.17.71 - - [08/Jan/2006:00:14:48 +0000] \&quot;GET /blog.ucw?entry-id=2 HTTP/1.1\&quot; 200 15016 \&quot;http://planet.lisp.org/\&quot; \&quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.2\&quot; \&quot;-\&quot;&quot;

COM.JALAT.LOGPARSE 40 &gt; (split-string (first *teststrings*))
(&quot;222.153.17.71&quot;)

&lt;/pre&gt;
&lt;p&gt;

As you can see, the (\\S+) has matched non-empty characters and is
stored in the variable ipaddr. &lt;code&gt;cl-ppcre&lt;/code&gt; returns the first match
it can find, that is why I get the ip address and not just any substring
consisting of non-whitespace. Why do I use \\S if \S is what matches a character?
\ is the quote character for strings in lisp so a simple \ will just pass &quot;S&quot; on 
to &lt;code&gt;cl-ppcre&lt;/code&gt;:

&lt;/p&gt;
&lt;pre&gt;


COM.JALAT.LOGPARSE 41 &gt; (princ &quot;\a&quot;)
a
&quot;a&quot;

COM.JALAT.LOGPARSE 42 &gt; (princ &quot;\\a&quot;)
\a
&quot;\\a&quot;

COM.JALAT.LOGPARSE 44 &gt; (length &quot;\a&quot;)
1

COM.JALAT.LOGPARSE 45 &gt; (length &quot;\\a&quot;)
2

&lt;/pre&gt;
&lt;p&gt;

I&#039;m not going to bother with the ip adresses. I guess it might be
useful if you want to try to count individual users, but then you
have to be clever about different user behind a proxy/NAT. So I 
won&#039;t be doing that. Too complicated for me, and who really wants
to reduce the percieved number of visitors anyway. I&#039;m doing this to 
boost my ego, after all.

&lt;/p&gt;
&lt;p&gt;

What I will do is to use the time data. I can&#039;t use \\S+ here since
there is a space in the string. What I&#039;ll do is read the first [ and
then collect all non-] characters.

&lt;/p&gt;
&lt;pre&gt;

(defun split-string (logstring)
    (register-groups-bind 
      (when) 
      (&quot;\\[([^\\]]*)\\]&quot; logstring)
    (list when)))

COM.JALAT.LOGPARSE 46 &gt; (split-string (first *teststrings*))
(&quot;08/Jan/2006:00:14:48 +0000&quot;)

&lt;/pre&gt;
&lt;p&gt;

As you can see, I have to quote (twice) the [&#039;s and ]&#039;s that are
literal, to stop them being interpreted as a [] directive. If you have
problems sorting out the expression above, it might help to eliminate
from outside and in starting with \\[ and \\]. Inside those are the (
) meaning that I want to collect the string matching the pattern
inside the ( ). Finally the inner expression [^\\]]* means 0 or more
characters that are not the character &#039;]&#039;

&lt;/p&gt;
&lt;p&gt;

I&#039;m a bit lucky because of the fact that there are no [] in the log
strings before the time description.  This means that I abuse the
fact that cl-ppcre returns the first match it finds. But this is 
not the best way of writing a regular expression if we want performance.
With this expression the scanner have to search the string for the
start of the expression. If we tell the scanner where the expression 
starts we can reduce the workload a bit:

&lt;/p&gt;
&lt;pre&gt;

(defun split-string (logstring)
    (register-groups-bind 
      (when) 
      (&quot;^\\S+ \\S+ \\S+ \\[([^\\]]*)\\]&quot; logstring)
    (list when)))

&lt;/pre&gt;
&lt;p&gt;

The ^ tells the scanner that our expression starts at the start of the
string, then there are three substrings separated by spaces that I&#039;m not interested
in. Finally there is the date string which I am interested in.

&lt;/p&gt;
&lt;p&gt;

Next is to extract the url. The url is surrounded by &quot;GET and
HTTPsomething&quot;. I&#039;m using a similar trick to what I used above to
match up to the &quot;.

&lt;/p&gt;
&lt;pre&gt;

(defun split-string (logstring)
    (register-groups-bind 
      (when request) 
      (&quot;^\\S+ \\S+ \\S+ \\[([^\\]]*)\\] \&quot;GET (\\S*) HTTP[^\\\&quot;]*\&quot;&quot; logstring)
    (list when request)))


COM.JALAT.LOGPARSE 5 &gt; (split-string (first *teststrings*))
(&quot;08/Jan/2006:00:14:48 +0000&quot; &quot;/blog.ucw?entry-id=2&quot;)

COM.JALAT.LOGPARSE 7 &gt; (split-string (second *teststrings*))
(&quot;08/Jan/2006:00:14:47 +0000&quot; &quot;/back-of-the-envelope.html&quot;)

&lt;/pre&gt;
&lt;p&gt;

Now, remember that this is only one request that is being redirected.
I don&#039;t really want to count it twice. The next element of the string
helps us sort out requests that has been answered successfully from
requests that fail, are redirected or don&#039;t exist. This element is the
result code, 200 means a successfull request so I&#039;ll hardcode 200 in
my regexp string. The field after the result code I&#039;ll skip by
matching but not collecting it. Then I&#039;ll collect the referring url. I want
to see who have been nice and linked to me.

&lt;/p&gt;
&lt;pre&gt;

(defun split-string (logstring)
    (register-groups-bind 
      (when request referrer) 
      (&quot;^\\S+ \\S+ \\S+ \\[([^\\]]*)\\] \&quot;GET (\\S*) HTTP[^\\\&quot;]*\&quot; 200 \\S+ \&quot;([^\\\&quot;]+)\&quot;&quot; logstring)
    (list when request referrer)))

COM.JALAT.LOGPARSE 9 &gt; (split-string (car *teststrings*))
(&quot;08/Jan/2006:00:14:48 +0000&quot; &quot;/blog.ucw?entry-id=2&quot; &quot;http://planet.lisp.org/&quot;)

COM.JALAT.LOGPARSE 10 &gt; (split-string (cadr *teststrings*))
NIL

&lt;/pre&gt;
&lt;p&gt;

One more detail, I don&#039;t like the date/time format, for now all I want is
the date. It would also be nice to have a more sortable date. I will do
this by splitting up the date string in days months year and combining
it to a number. &lt;code&gt;\d{2}&lt;/code&gt; will match two digits (the day part),
&lt;code&gt;\w{3}&lt;/code&gt; three alphanumeric character (month) and &lt;code&gt;\d{4}&lt;/code&gt;
the year.

&lt;/p&gt;
&lt;pre&gt;

(defparameter *months* &#039;((&quot;Jan&quot; . &quot;01&quot;) (&quot;Feb&quot; . &quot;02&quot;) (&quot;Mar&quot; . &quot;03&quot;)
                         (&quot;Apr&quot; . &quot;04&quot;) (&quot;May&quot; . &quot;05&quot;) (&quot;Jun&quot; . &quot;06&quot;)
                         (&quot;Jul&quot; . &quot;07&quot;) (&quot;Aug&quot; . &quot;08&quot;) (&quot;Sep&quot; . &quot;09&quot;)
                         (&quot;Oct&quot; . &quot;10&quot;) (&quot;Nov&quot; . &quot;11&quot;) (&quot;Dec&quot; . &quot;12&quot;)))

(defun numerical-date (date month year)
  (parse-integer 
   (concatenate &#039;string
                year
                (cdr (assoc month *months* :test #&#039;string=))
                date)))

(defun split-string (logstring)
    (register-groups-bind 
      (date month year request referrer) 
      (&quot;^\\S+ \\S+ \\S+ \\[(\\d{2})/(\\w{3})/(\\d{4})[^\\]]*\\] \&quot;GET (\\S*) HTTP[^\\\&quot;]*\&quot; 200 \\S+ \&quot;([^\\\&quot;]+)\&quot;&quot; logstring)
    (list (numerical-date date month year) request referrer)))

COM.JALAT.LOGPARSE 34 &gt; (split-string (car *teststrings*))
(20060108 &quot;/blog.ucw?entry-id=2&quot; &quot;http://planet.lisp.org/&quot;)

&lt;/pre&gt;
&lt;p&gt;

Ok, time to start counting. I&#039;m just going to start with a hash-table
of dates and count how many requests I get for each date. I will also move
the regexp out of the record-string function, so the regexp scanner only
have to be built once. This should increase the performance a bit. 

&lt;/p&gt;
&lt;pre&gt;

(defparameter *logscanner* (create-scanner &quot;^\\S+ \\S+ \\S+ \\[(\\d{2})/(\\w{3})/(\\d{4})[^\\]]*\\] \&quot;GET (\\S*) HTTP[^\\\&quot;]*\&quot; 200 \\S+ \&quot;([^\\\&quot;]+)\&quot;&quot;))
(defparameter *datehash* (make-hash-table))

(defun record-entry (date request referrer)
  (declare (ignore request referrer))
  (let* ((currentcount (gethash date *datehash* 0)))
    (setf (gethash date *datehash*) (1+ currentcount))))

(defun record-string (logstring)
    (register-groups-bind 
      (day month year request referrer) 
      (*logscanner* logstring)
      (record-entry (numerical-date day month year) request referrer)))

(defun parse-file (filename)
  (with-open-file (s filename)
    (do ((string (read-line s) (read-line s nil &#039;eof)))
        ((eql string &#039;eof) nil)
      (record-string string))))

(defun printstats (filename)
  (parse-file filename)
  (dolist (x (sort 
               (loop for k being the hash-key of *datehash*
                     collect (list k (gethash k *datehash*)))
               #&#039;&gt;
               :key #&#039;car))
    (format t &quot;~a ~a~%&quot; (car x) (cadr x))))


COM.JALAT.LOGPARSE 28 &gt; (printstats &quot;~/poundlog&quot;)
20060128 1986
20060127 325
20060126 33
20060125 29
20060124 39
20060123 25
20060122 73
20060121 30
20060120 32
20060119 67
20060118 103
20060117 116
20060116 96
20060115 98
20060114 89
20060113 130
20060112 123

&lt;/pre&gt;
&lt;p&gt;

The code above is quite simple I hope, &lt;code&gt;create-scanner&lt;/code&gt;
creates a closure that I use in the now renamed
&lt;code&gt;record-string&lt;/code&gt;. The result is passed on to
&lt;code&gt;record-entry&lt;/code&gt; that updates the hash table of hits.
&lt;code&gt;parse-file&lt;/code&gt; loops through a file calling
&lt;code&gt;record-string&lt;/code&gt; for each line. &lt;code&gt;printstats&lt;/code&gt; just
prints out the keys/values of the hash table.

&lt;/p&gt;
&lt;p&gt;

Ok, this raises the obvious question, what happened on the 27/28 of January? 
30 visitors a day is unlikely enough (I&#039;m not going to bother showing this, but
there is a surprisingly large amount of bots traversing the net :) so what on 
earth triggered almost 2000 requests on the 28th? Let&#039;s have a look at where 
they come from. Instead of keeping a single number for each date, I&#039;ll have a 
hash table for each date, and in that hash table record the number of times
each url appear as a referrer:

&lt;/p&gt;
&lt;pre&gt;


(defun record-entry (date request referrer)
  (declare (ignore request))
  (let* ((referrerhash (gethash date *datehash* (make-hash-table :test &#039;equal))))
    (incf (gethash referrer referrerhash 0))
    (setf (gethash date *datehash*) referrerhash)))

&lt;/pre&gt;
&lt;p&gt;

Hash tables by default uses eql to compare values. This works well with
the numerical key I use for the dates, but won&#039;t work too well for the 
url strings. That is why I the :test argument to choose a different
equality test. The possible choices are eq, eql, equal and equalp.
For string keys equal will do nicely.

&lt;/p&gt;
&lt;pre&gt;

(defun printstats (filename)
  (setf *datehash* (make-hash-table))
  (parse-file filename)
  (dolist (date-entry (sort 
                       (loop for k being the hash-key of *datehash*
                             collect (list k (gethash k *datehash*)))
                       #&#039;&gt;
                       :key #&#039;first))
    (format t &quot;~%~a:~%&quot; (first date-entry))
    (dolist (referrer (sort 
                       (loop for k being the hash-key of (second date-entry)
                             collect (list k (gethash k (second date-entry))))
                       #&#039;&gt;
                       :key #&#039;second))
      (format t &quot;  ~a ~a~%&quot; (second referrer) (first referrer)))))

&lt;/pre&gt;
&lt;p&gt;

&lt;code&gt;printstats&lt;/code&gt; is updated with an inner loop that loops over
the hashes in the date hashtable, sorting by the number of request from
the url. And the result:

&lt;/p&gt;
&lt;pre&gt;

COM.JALAT.LOGPARSE 19 &gt; (printstats &quot;~/poundlog&quot;)

20060128:
  621 http://www.jalat.com/blogs/lisp
  433 http://www.jalat.com/blogs/lisp?id=4
  242 http://planet.lisp.org/
  153 http://www.jalat.com/
  113 http://www.jalat.com/blogs/lisp?id=3
  67 http://www.jalat.com/blogs/lisp?id=1
  53 http://www.jalat.com/blogs/lisp?id=2
  42 http://weitz.de/hunchentoot/
  40 http://lemonodor.com/archives/001339.html
  31 http://lemonodor.com/
  28 http://www.lemonodor.com/
  17 http://www.google.com/reader/lens/
  7 http://keithdevens.com/weblog
  5 http://anarchaia.org/

&lt;/pre&gt;
&lt;p&gt;

I cut off most of this list, it&#039;s 108 different referrers for the 28th
january and while there are some interesting entries there, they are
not responsible for the spike on the 27/28th. It turns out quite a few
people read &lt;a href=&quot;http://planet.lisp.org/&quot;&gt;http://planet.lisp.org&lt;/a&gt;
and that Mr. John Wiseman aka. &lt;a href=&quot;http://lemonodor.com/archives/001339.html&quot;&gt;lemonodor&lt;/a&gt;
mentioned my ramblings in his blog which happens to be aggregated on 
planet.lisp.org. Gotta say that is one cool urinal shot, too. And with
a camera phone, wow!. Maybe they&#039;re not as useless as I thought.

&lt;/p&gt;
&lt;p&gt;

Anyway, the biggest referrer seems to be myself. Mostly links
to images, is my guess. Shouldn&#039;t be too hard to check. In fact, since
is is possible to use a list as a key to the hash table, I only have
to make the key to my hash a list of (referrer request). A simple two
line change:

&lt;/p&gt;
&lt;pre&gt;

(defun record-entry (date request referrer)
  (let* ((referrerhash (gethash date *datehash* (make-hash-table :test &#039;equal))))
    (incf (gethash (list referrer request) referrerhash 0)) 
    (setf (gethash date *datehash*) referrerhash)))

(defun printstats (filename)
  (setf *datehash* (make-hash-table))
  (parse-file filename)
  (dolist (date-entry (sort 
                       (loop for k being the hash-key of *datehash*
                             collect (list k (gethash k *datehash*)))
                       #&#039;&gt;
                       :key #&#039;first))
    (format t &quot;~%~a:~%&quot; (first date-entry))
    (dolist (referrer (sort 
                       (loop for k being the hash-key of (second date-entry)
                             collect (list k (gethash k (second date-entry))))
                       #&#039;&gt;
                       :key #&#039;second))
      (format t &quot;  ~a ~a =&gt; ~a~%&quot; (second referrer) (first (first referrer)) (second (first referrer)))))
  *datehash*)


COM.JALAT.LOGPARSE 22 &gt; (printstats &quot;~/poundlog&quot;)

20060128:
  266 http://www.jalat.com/blogs/lisp =&gt; /static-files/pieces.gif
  227 http://www.jalat.com/blogs/lisp =&gt; /static-files/stylesheet.css
  197 http://www.jalat.com/blogs/lisp?id=4 =&gt; /static-files/pieces.gif
  186 http://www.jalat.com/blogs/lisp?id=4 =&gt; /static-files/stylesheet.css
  96 http://planet.lisp.org/ =&gt; /blogs/lisp?id=4
  94 http://planet.lisp.org/ =&gt; /blogs/lisp
  85 http://www.jalat.com/ =&gt; /blogs/lisp
  54 http://www.jalat.com/blogs/lisp =&gt; /blogs/lisp?id=3
  53 http://www.jalat.com/blogs/lisp?id=3 =&gt; /static-files/stylesheet.css
  52 http://planet.lisp.org/ =&gt; /blogs/lisp?id=3
  42 http://weitz.de/hunchentoot/ =&gt; /
  40 http://www.jalat.com/ =&gt; /static-files/stylesheet.css
  33 http://www.jalat.com/blogs/lisp?id=2 =&gt; /blogs/lisp?id=1
  31 http://www.jalat.com/blogs/lisp?id=3 =&gt; /blogs/lisp?id=2
  29 http://www.jalat.com/blogs/lisp?id=1 =&gt; /static-files/flipper-linux.jpg
  24 http://www.jalat.com/blogs/lisp =&gt; /blogs/lisp?id=1
  21 http://lemonodor.com/archives/001339.html =&gt; /blogs/lisp

&lt;/pre&gt;
&lt;p&gt;

Not just pictures it seems. The stylesheet is a big contributor as
well.  I&#039;m not all that interested in this as they aren&#039;t really hits,
so I&#039;m going to filter it out.  At the same time i&#039;ll add in the
missing hostname for the request strings.

&lt;/p&gt;
&lt;pre&gt;

(defun record-entry (date request referrer)
  (unless (scan &quot;static-files|favicon.ico|flipper-linux.jpg&quot; request)
    (let* ((referrerhash (gethash date *datehash* (make-hash-table :test &#039;equal)))
           (full-request (concatenate &#039;string &quot;http://www.jalat.com&quot; request)))
      (incf (gethash (list referrer full-request) referrerhash 0))
      (setf (gethash date *datehash*) referrerhash))))

&lt;/pre&gt;
&lt;p&gt;

&lt;code&gt;scan&lt;/code&gt; is another function from &lt;code&gt;cl-ppcre&lt;/code&gt;. It returns
indexes to where the pattern is found in the string, or nil if the pattern is
not found. I&#039;m not interested in the index, but simply use it as a true/false
test for if the pattern is in the string. The resulting output is:

&lt;/p&gt;
&lt;pre&gt;

20060128:
  96 http://planet.lisp.org/ =&gt; http://www.jalat.com/blogs/lisp?id=4
  94 http://planet.lisp.org/ =&gt; http://www.jalat.com/blogs/lisp
  85 http://www.jalat.com/ =&gt; http://www.jalat.com/blogs/lisp
  54 http://www.jalat.com/blogs/lisp =&gt; http://www.jalat.com/blogs/lisp?id=3
  52 http://planet.lisp.org/ =&gt; http://www.jalat.com/blogs/lisp?id=3
  42 http://weitz.de/hunchentoot/ =&gt; http://www.jalat.com/
  33 http://www.jalat.com/blogs/lisp?id=2 =&gt; http://www.jalat.com/blogs/lisp?id=1
  31 http://www.jalat.com/blogs/lisp?id=3 =&gt; http://www.jalat.com/blogs/lisp?id=2
  24 http://www.jalat.com/blogs/lisp =&gt; http://www.jalat.com/blogs/lisp?id=1
  21 http://lemonodor.com/archives/001339.html =&gt; http://www.jalat.com/blogs/lisp
  16 http://www.jalat.com/blogs/lisp =&gt; http://www.jalat.com/blogs/lisp?id=2
  16 http://www.jalat.com/blogs/lisp?id=1 =&gt; http://www.jalat.com/blogs/lisp?id=2
  15 http://www.jalat.com/blogs/lisp?id=3 =&gt; http://www.jalat.com/blogs/lisp?id=1
  15 http://www.jalat.com/blogs/lisp?id=4 =&gt; http://www.jalat.com/blogs/lisp?id=3
  15 http://lemonodor.com/archives/001339.html =&gt; http://www.jalat.com/blogs/lisp?id=4
  12 http://www.lemonodor.com/ =&gt; http://www.jalat.com/blogs/lisp
  12 http://www.lemonodor.com/ =&gt; http://www.jalat.com/blogs/lisp?id=4
  12 http://lemonodor.com/ =&gt; http://www.jalat.com/blogs/lisp
  11 http://lemonodor.com/ =&gt; http://www.jalat.com/blogs/lisp?id=4

&lt;/pre&gt;
&lt;p&gt;

It works even though it&#039;s not that pretty. I&#039;m going to leave it at
that anyway, because I&#039;m trying to shorten these blog entries and I&#039;ve
hopefully demonstrated some regexps and hash table usage by now. Throw
it into a table for more presentable output. And you probably want to
combine www.domain.name and domain.name urls. I&#039;m going to finish off
with someting a bit different:

&lt;/p&gt;
&lt;p&gt;

&lt;a href=&quot;http://www.cliki.net/cl-dot&quot;&gt;CL-DOT&lt;/a&gt; is a package by 
&lt;a href=&quot;http://jsnell.iki.fi/blog/archive/2005-11-05.html&quot;&gt;Juho Snellman&lt;/a&gt; 
that makes it easy to make data files for the dot program in the Graphviz suite.
It works by defining methods that describe how different objects should be
represented, and then passing a data structure to &lt;code&gt;generate-graph&lt;/code&gt;.

&lt;/p&gt;
&lt;p&gt;

&lt;code&gt;generate-graph&lt;/code&gt; will generate a graph that can be saved in
different ways, I just save it to a dot file, and later use dot to
generate the picture.  It is also possible to have &lt;code&gt;cl-dot&lt;/code&gt;
generate ps/jpeg/etc. directly.

&lt;/p&gt;
&lt;pre&gt;
(defparameter *dothash* (make-hash-table))

(defun record-entry (date request referrer)
  (unless (scan &quot;static-files&quot; request)
    (let* ((referrerhash (gethash date *datehash* (make-hash-table)))
           (interned-request (intern (concatenate &#039;string &quot;http://www.jalat.com&quot; request)))
           (interned-referrer (intern referrer))
           (ref-dothash (gethash interned-referrer *dothash* (make-hash-table))))
      (incf (gethash (list interned-referrer interned-request) referrerhash 0))
      (setf (gethash date *datehash*) referrerhash)
      (incf (gethash interned-request ref-dothash 0))
      (incf (gethash :num-referrals ref-dothash 0))
      (setf (gethash interned-referrer *dothash*) ref-dothash))))

&lt;/pre&gt;
&lt;p&gt;

I have to make one workaround. &lt;code&gt;cl-dot&lt;/code&gt; keeps track of
object by keeping them in a hash. That means that I have to turn the
strings into symbols. &lt;code&gt;intern&lt;/code&gt; does just that. &lt;code&gt;*dothash*&lt;/code&gt;
Each entry in the *dothash* hash has a url  as a key and the value is
another hash which lists the urls the first url refers to and the number
of times it refers to them. I&#039;m also putting in a special symbol
&lt;code&gt;:num-referrals&lt;/code&gt; that contains the sum of the urls referrals.

&lt;/p&gt;
&lt;p&gt;

BTW: The use of hash tables here is a bit dubious. Each url usually
only refers to a couple of other urls. So the hash tables are very
small, and the overhead is high. A list would probably have been a more
efficient choice.

&lt;/p&gt;
&lt;pre&gt;

(defpackage :com.jalat.logparse
  (:use :cl :cl-ppcre :cl-dot))

(defmethod object-node ((object list))
  nil)

(defmethod object-knows-of ((object list))
  object)

&lt;/pre&gt;
&lt;p&gt;

I&#039;m going to pass a bunch of urls in a list to the
&lt;code&gt;generate-graph&lt;/code&gt; function. I don&#039;t want to print the list in 
the graph, it&#039;s just a container for the data, so object-node for lists
just return nil. I do need cl-dot to model the contents of the list, so I have
to make the contents known. I do this with the object-knows-of method.

&lt;/p&gt;
&lt;pre&gt;

(defmethod object-node ((object symbol))
  (make-instance &#039;node
                 :attributes (list :label object
                                   :shape :box)))

(defmethod object-points-to ((object symbol))
  (let ((reqhash (gethash object *dothash*)))
    (when reqhash
      (remove-if &#039;null
                 (loop for i being the hash-key of reqhash
                       collect (unless (eql :num-referrals i)
                                 (make-instance &#039;attributed
                                                :object i
                                                :attributes (list :label (gethash i reqhash)))))))))

&lt;/pre&gt;
&lt;p&gt;

I&#039;m going to represent symbols (urls) as boxes, and the symbol itself
as the label of the box. Urls point to other urls, finding the urls
this url refers to is as simple as looking it up in the *dothash* table and 
removing the &lt;code&gt;:num-referrals&lt;/code&gt; symbol.

&lt;/p&gt;
&lt;pre&gt;

(defun make-graph (filename)
  (with-open-file (out filename :direction :output :if-exists :supersede)
    (cl-dot:print-graph
     (cl-dot:generate-graph 
      (mapcar #&#039;first
              (subseq (sort (loop for k being the hash-key of *dothash*
                                  collect (let ((refhash (gethash k *dothash*)))
                                            (list k (gethash :num-referrals refhash))))
                            #&#039;&gt;
                            :key #&#039;second)
                      0 20)))
     out)))



&lt;/pre&gt;
&lt;p&gt;

I could just generate a huge graph with all the urls, but it gets
quite messy.  Here the loop generates a list of &lt;code&gt;(url
num-referrals)&lt;/code&gt;, &lt;code&gt;sort&lt;/code&gt; sorts it based on the
num-referrals, &lt;code&gt;subseq&lt;/code&gt; makes alist of the first 20,
&lt;code&gt;mapcar&lt;/code&gt; makes a list of only the urls, &lt;code&gt;generate-graph&lt;/code&gt;
makes the graph, and &lt;code&gt;print-graph&lt;/code&gt; writes it to a file. 

&lt;/p&gt;
&lt;p&gt;

Using dot I can now generate a 
&lt;a href=&quot;http://www.jalat.com/static-files/referrer-graph.gif&quot;&gt;
graph of the top referring urls&lt;/a&gt; to my site. As you can see it&#039;s
a bit messy even with 20 urls. I think it&#039;s kind of neat in a way. 

&lt;/p&gt;
&lt;p&gt;
As usual: Feedback welcome at &lt;a href=&quot;mailto:asbjxrn@bjxrnstad.net&quot;&gt;asbjxrn@bjxrnstad.net&lt;/a&gt;
&lt;/p&gt;
</description>
    </item>
    <item>
      <title>Let's dance</title>
      <link>http://www.jalat.com/blogs/lisp?id=4</link>
      <pubDate>Sun, 16 Jan 2006 12:56:57 GMT</pubDate>
      <description>
&lt;p&gt;

There is this &lt;a href=&quot;http://www.sudoku.com/&quot;&gt;sudoku craze&lt;/a&gt; going
around the world. I got to admit, for a while I were writing numbers
in squares as well. But I (quickly, I like to think.) realized that it
was basically just different ways of counting which numbers are
already used and filling in the rest, and repeat the process over and
over and over again.

&lt;/p&gt;
&lt;p&gt;

Computers are good at counting, I thought, so I wrote a program to do
the work for me. Using the same logic I did myself to eliminate
choices and filling in squares when only one choice were left for a
square. It worked well for a while, but then I found a puzzle it
didn&#039;t solve, and I had to add some more rules.  And it worked for a
while, but then I found another puzzle. And so on.

&lt;/p&gt;
&lt;p&gt;

I&#039;m not going to show you that program. I finally gave up on the logic
approach, you never know if there is some pattern you have missed
until you stumble upon it. Instead I going to show the brute force
approach.  It&#039;s not obvious how well that would work, sudoku puzzles
with as few as &lt;a
href=&quot;http://www.csse.uwa.edu.au/~gordon/sudoku17&quot;&gt;17 starting
hints&lt;/a&gt; are known.  Without doing any kind of narrowing of the
search, that means there are &lt;code&gt;(expt 9 (- 81 17))&lt;/code&gt;
combinations to search through.  That is a big number.

&lt;/p&gt;
&lt;p&gt;

Luckily, smarter people than me have played around with sudoku as well.
And one of them, &lt;a href=&quot;http://www-cs-faculty.stanford.edu/~knuth/&quot;&gt;
Donald E. Knuth&lt;/a&gt;, has come up with an algorithm that&#039;s pretty good.
He calls it &lt;a href=&quot;http://www-cs-faculty.stanford.edu/~knuth/papers/dancing-color.ps.gz&quot;&gt;
&quot;Dancing links&quot;&lt;/a&gt;. Actually, he didn&#039;t really make it to solve sudokus, 
Knuth wanted to pack shapes into a container. 

&lt;/p&gt;
&lt;p&gt;

A small example. Suppose you have the following pieces &lt;img
src=&quot;../static-files/pieces.gif&quot;&gt; and want to pack them onto a 3x3
square, without rotating any of them.  To solve this problem you could
set up a matrix so that each row represents a placement of a piece.
The first 9 columns represent the squares in the 3x3 square. The last
three columns represent the piece used for that row (marked L, B and S
for L-shape, Big square and Small square.) We get something like this
(I&#039;m using _ to make it easier to read):

&lt;/p&gt;
&lt;pre&gt;
                         L B S
                      
1)  1 1 1  1 _ _  _ _ _  1 _ _    ; L in top/middle row.
2)  _ _ _  1 1 1  1 _ _  1 _ _    ; L in middle/bottom row
3)  1 1 _  1 1 _  _ _ _  _ 1 _    ; Big square in top left corner
4)  _ 1 1  _ 1 1  _ _ _  _ 1 _    ; Big square in top right corner
5)  _ _ _  1 1 _  1 1 _  _ 1 _    ; Big square in bottom left corner
6)  _ _ _  _ 1 1  _ 1 1  _ 1 _    ; Big square in bottom right corner
7)  1 _ _  _ _ _  _ _ _  _ _ 1    ; Small square top left
8)  _ 1 _  _ _ _  _ _ _  _ _ 1    ; Small square top middle 
9)  _ _ 1  _ _ _  _ _ _  _ _ 1    ; etc.
10) _ _ _  1 _ _  _ _ _  _ _ 1
11) _ _ _  _ 1 _  _ _ _  _ _ 1
12) _ _ _  _ _ 1  _ _ _  _ _ 1
13) _ _ _  _ _ _  1 _ _  _ _ 1
14) _ _ _  _ _ _  _ 1 _  _ _ 1
15) _ _ _  _ _ _  _ _ 1  _ _ 1
&lt;/pre&gt;
&lt;p&gt;

Now we can restate the problem. We will select rows in such a way that
if we add up the selected rows we get one and only one one (1) in each
column. In this example row 1, 6 and 13 solves the problem. Note also
that the last three columns while not representing a square that needs
to be filled on the board, is treated no differently.

&lt;/p&gt;
&lt;p&gt;

We can look at each column as a constraint. The last three columns
forces us to use each piece only once. And the first nine columns
forces us to use each square of the board only once.

&lt;/p&gt;
&lt;p&gt;

Now if you&#039;re anything like me you would solve this by first picking
the first row, then mentally remove all rows that have a 1 in any of
the columns where the first row has a 1.  Then mentally remove the
columns where the row has a 1 and then looking for the first row that
has a 1 in the remaining columns, then repeat that process until there
are no more columns to fill. If you had started out with the third row
instead of the first row, you would at one point have realized that
you couldn&#039;t solve the puzzle, and you would put the columns rows back
in and chosen another row. You could just start over, but that&#039;s
inefficient for big puzzles.

&lt;/p&gt;
&lt;p&gt;

Let&#039;s make another small puzzle, fill a 3x3 square, and usethe numbers
1, 2 and 3 in it so that each row and column have all three numbers in
them, but only once in each row (Obviously). I&#039;ll make a matrix based
on the row, column and value of the number in the square like this:

&lt;/p&gt;
&lt;pre&gt;

r,c=v         r,c                r,v                c,v
             
1,1=1   1 _ _ _ _ _ _ _ _  1 _ _ _ _ _ _ _ _  1 _ _ _ _ _ _ _ _
1,1=2   1 _ _ _ _ _ _ _ _  _ 1 _ _ _ _ _ _ _  _ 1 _ _ _ _ _ _ _
1,1=3   1 _ _ _ _ _ _ _ _  _ _ 1 _ _ _ _ _ _  _ _ 1 _ _ _ _ _ _
1,2=1   _ 1 _ _ _ _ _ _ _  1 _ _ _ _ _ _ _ _  _ _ _ 1 _ _ _ _ _
1,2=2   _ 1 _ _ _ _ _ _ _  _ 1 _ _ _ _ _ _ _  _ _ _ _ 1 _ _ _ _
1,2=3   _ 1 _ _ _ _ _ _ _  _ _ 1 _ _ _ _ _ _  _ _ _ _ _ 1 _ _ _
1,3=1   _ _ 1 _ _ _ _ _ _  1 _ _ _ _ _ _ _ _  _ _ _ _ _ _ 1 _ _
1,3=1   _ _ 1 _ _ _ _ _ _  _ 1 _ _ _ _ _ _ _  _ _ _ _ _ _ _ 1 _
1,3=1   _ _ 1 _ _ _ _ _ _  _ _ 1 _ _ _ _ _ _  _ _ _ _ _ _ _ _ 1

             
2,1=1   _ _ _ 1 _ _ _ _ _  _ _ _ 1 _ _ _ _ _  1 _ _ _ _ _ _ _ _
2,1=2   _ _ _ 1 _ _ _ _ _  _ _ _ _ 1 _ _ _ _  _ 1 _ _ _ _ _ _ _
2,1=3   _ _ _ 1 _ _ _ _ _  _ _ _ _ _ 1 _ _ _  _ _ 1 _ _ _ _ _ _
2,2=1   _ _ _ _ 1 _ _ _ _  _ _ _ 1 _ _ _ _ _  _ _ _ 1 _ _ _ _ _
2,2=2   _ _ _ _ 1 _ _ _ _  _ _ _ _ 1 _ _ _ _  _ _ _ _ 1 _ _ _ _
2,2=3   _ _ _ _ 1 _ _ _ _  _ _ _ _ _ 1 _ _ _  _ _ _ _ _ 1 _ _ _
2,3=1   _ _ _ _ _ 1 _ _ _  _ _ _ 1 _ _ _ _ _  _ _ _ _ _ _ 1 _ _
2,3=1   _ _ _ _ _ 1 _ _ _  _ _ _ _ 1 _ _ _ _  _ _ _ _ _ _ _ 1 _
2,3=1   _ _ _ _ _ 1 _ _ _  _ _ _ _ _ 1 _ _ _  _ _ _ _ _ _ _ _ 1

             
3,1=1   _ _ _ _ _ _ 1 _ _  _ _ _ _ _ _ 1 _ _  1 _ _ _ _ _ _ _ _
3,1=2   _ _ _ _ _ _ 1 _ _  _ _ _ _ _ _ _ 1 _  _ 1 _ _ _ _ _ _ _
3,1=3   _ _ _ _ _ _ 1 _ _  _ _ _ _ _ _ _ _ 1  _ _ 1 _ _ _ _ _ _
3,2=1   _ _ _ _ _ _ _ 1 _  _ _ _ _ _ _ 1 _ _  _ _ _ 1 _ _ _ _ _
3,2=2   _ _ _ _ _ _ _ 1 _  _ _ _ _ _ _ _ 1 _  _ _ _ _ 1 _ _ _ _
3,2=3   _ _ _ _ _ _ _ 1 _  _ _ _ _ _ _ _ _ 1  _ _ _ _ _ 1 _ _ _
3,3=1   _ _ _ _ _ _ _ _ 1  _ _ _ _ _ _ 1 _ _  _ _ _ _ _ _ 1 _ _
3,3=1   _ _ _ _ _ _ _ _ 1  _ _ _ _ _ _ _ 1 _  _ _ _ _ _ _ _ 1 _
3,3=1   _ _ _ _ _ _ _ _ 1  _ _ _ _ _ _ _ _ 1  _ _ _ _ _ _ _ _ 1

&lt;/pre
&lt;p&gt;

If we now do as above and choose rows out of this matrix such that we
get one and only one one (1) for each column, you can see that the first
9 columns of the matrix forces us to choose only one value for each pair r,c.
The next 9 columns forces us to only use each value only once for each row
r,v. And the last columns forces us to only use each value once for each column
c,v.

&lt;/p&gt;
&lt;p&gt;

This is almost how I&#039;m going to represent the sudoku puzzle, soduku
have one more constraint, the 9x9 square is divided into 9 3x3 blocs,
and each block also have to contain the numbers 1-9. This is easy
enough to accomplish. We just add another block to our matrix, so in
addtion to (r,c) (r,v) (c,v) we have (b,v).  This means our matrix is
big enough that I&#039;m not going to bother writing it out. Each row
has 81 columns for the (r,c) constraint, 81 columns for (r,v), 81
columns for (c,v) and 81 columns for (b,v) =&gt; 364 columns. And the
matrix has one row for each combination of r,c,v =&gt; 9*9*9 =&gt; 729 rows.

&lt;/p&gt;
&lt;p&gt;

The point I wanted to illustrate with this detour before I start
describing the algorithm is that you don&#039;t have to come up
with a completely new algorithm for a problem if you know a good
algorithm that can be used if you look at the problem in a different
way.

&lt;/p&gt;
&lt;p&gt;

When representing a matrix, it could be tempting to represent it as an
array. It is probaly the most common way of representing matrixes.
However, Knuth used double-linked circular lists for this algorithm,
and for a good reason.  When you remove an element from a
double-linked list, the element remembers it&#039;s position in the list if
you don&#039;t change the elements next/previous pointers. This makes it
very easy to reinsert the element again. So when we guess wrong in
our algorithm it is easy to backtrack a few steps.

&lt;/p&gt;
&lt;p&gt;

The only thing to watch out for is to reinsert the elements in the
opposite order they were taken out of the list, which is what you
would do in a depth first search anyway.

&lt;/p&gt;
&lt;p&gt;

So what is the data structure going to look like?
&lt;ul&gt;
&lt;li&gt;Each &quot;1&quot; will be represented by a matrix element, we will not represent
    the gaps in the matrix in any way. They are not interesting.

&lt;li&gt;Each element get a left and right pointer which points to the
    previous/next element in the row. It&#039;s a circular list, so the first and the
    last element in each row points to each other.&lt;/li&gt;

&lt;li&gt;Each element also get a up/down pointer with points to the
    previous/next element in the column. The top and bottom element points to a
    special element that is the header for that column. &lt;/li&gt;

&lt;li&gt;Header elements have right/left pointers to each other in a doubly linked 
    list as well. The first and the last header element points to a node that 
    is our entry point to the whole matrix.&lt;/li&gt;

&lt;li&gt;The header elements also has a name slot, which is not really
    neccessary but useful during debugging, and a size slot, which is the
    number of elements left in that column. We&#039;ll choose columns to search
    based on how many elements are left in the columns. If we search the
    column with the smallest number of elements first, we will reduce the search
    tree and the whole thing will go a lot faster.&lt;/li&gt;

&lt;li&gt;Each node in the matrix also has extra slots, one triplet representing
    (row column value). This is used to print out the solution. And they also
    have a pointer to the header element of the column they are in.&lt;/li&gt;

&lt;li&gt;Finally, I&#039;m going to make a array with one element for each row in the
    matrix, this will point to the first element on each row, and it will 
    be used when setting up the starting position.&lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;
&lt;p&gt;

The whole thing should look someting like, oh, buggr&#039;it, go read
Knuths paper. It&#039;s got pretty pictures and stuff. Maybe I&#039;ll be 
bored enough one day to add a diagram here.

&lt;/p&gt;
&lt;p&gt;

With that out of the way, on to the implementation:

&lt;/p&gt;
&lt;pre&gt;

(defpackage :sudoku
    (:use :common-lisp))
  
(in-package :sudoku)

(defclass matrix-element ()
  ((up :accessor up :initarg :up)
   (down :accessor down :initarg :down)
   (left :accessor left :initarg :left)
   (right :accessor right :initarg :right)))

&lt;/pre&gt;
&lt;p&gt;

Now, if I were very concerned about performance I might use something
else than classes for this, but Knuth says premature optimization is
evil, so I wont. Besides, the best optimization is to use a good algorithm,
which I think I&#039;m doing. It&#039;s not like I made it myself.

&lt;/p&gt;
&lt;pre&gt;

(defmethod initialize-instance :after ((me matrix-element) &amp;rest initargs &amp;key &amp;allow-other-keys)
  (setf (up me) me)
  (setf (down me) me)
  (setf (left me) me)
  (setf (right me) me))

&lt;/pre&gt;
&lt;p&gt;

Once nice thing about classes is that you can make them do stuff when
you initialize them by adding an :after method on the
initialize-instance method. What I do above is to initialize all the
pointers of the matrix element to point back at the newly created
element instance. This means that a newly created instance is a tiny
circular list with itself as the only object and I don&#039;t have to worry
about wheter a single element is a list or not, I just treat
everything as lists.

&lt;/p&gt;
&lt;pre&gt;

(defclass column-header (matrix-element)
  ((size :accessor size :initform 0)
   (name :accessor name :initarg :name)))

(defclass column-element (matrix-element)
  ((column-header :accessor column-header :initarg :column-header)
   (triplet :accessor triplet :initarg :triplet)))

&lt;/pre&gt;
&lt;p&gt;

I&#039;m creating two subclasses, to add slots for the column headers and
the matrix elements as I mentioned above.

&lt;/p&gt;
&lt;pre&gt;

(defun insert-above (element new)
  &quot;Insert a new element above the existing element. And increase size of column by 1&quot;
  (setf (up new) (up element)
        (down new) element
        (down (up element)) new
        (up element) new)
  (incf (size (column-header new)))
  element)

(defun insert-rightof (element new)
  (setf (right new) (right element)
        (left new) element
        (left (right element)) new
        (right element) new)
  element)

&lt;/pre&gt;
&lt;p&gt;

Our insertion functions. I&#039;m building up the matrix right to left and
top to bottom. Since the columns are circular lists the easiest way to insert 
an element at the bottom of the list is to insert it above the column header.

&lt;/p&gt;
&lt;pre&gt;

(defmethod initialize-instance :after ((me column-element) &amp;rest initargs &amp;key &amp;allow-other-keys)
  (if (column-header me)
    (insert-above (column-header me) me)))

&lt;/pre&gt;
&lt;p&gt;

When I initialize the matrix elements I&#039;m going to pass the column
header as an argument to the make-instance call. This method puts
the element into the circular list for that column.

&lt;/p&gt;
&lt;pre&gt;

(defun remove-horizontal (element)
  (setf (left (right element)) (left element)
        (right (left element)) (right element))
  element)

(defun replace-horizontal (element)
  (setf (left (right element)) element
        (right (left element)) element)
  element)

&lt;/pre&gt;
&lt;p&gt;

The core of the algorithm, removing and replacing an element from a
list. These elements assumes that when you reinsert the element, the
list is in the same state as it was when the element was removed, in
other words, that &lt;code&gt;(left element)&lt;/code&gt; and &lt;code&gt;(right
element)&lt;/code&gt; points to each other.

&lt;/p&gt;
&lt;pre&gt;
(defun remove-vertical (element)
  (setf (up (down element)) (up element)
        (down (up element)) (down element))
  (decf (size (column-header element)))
  element)

(defun replace-vertical (element)
  (setf (up (down element)) element
        (down (up element)) element)
  (incf (size (column-header element)))  
  element)

&lt;/pre&gt;
&lt;p&gt;

Same thing vertically, this time I update the size of the column as well.

&lt;/p&gt;
&lt;pre&gt;

(defmacro rcv-loop (&amp;rest body)
  `(loop for r from 0 to 8
         do (loop for c from 0 to 8
                  do (loop for v from 0 to 8
                           do ,@body))))


&lt;/pre&gt;
&lt;p&gt;

A macro that I&#039;m going to use to build up the matrix. This is probably
bad style since I rely on body using the variables r c and v. 

&lt;/p&gt;
&lt;pre&gt;

(defun add-constraint-headers (matrix elem1 elem2)
  (loop for i from 0 to 8
        do (loop for j from 0 to 8
            do (insert-rightof (left matrix) 
                               (make-instance &#039;column-header
                                              :name (format nil &quot;~a: ~a/~a: ~a&quot; elem1 (+ 1 i) elem2 (+ 1 j)))))))

(defun sudoinit ()
  &quot;returns an initial matrix representing an empty board.&quot;
  (let ((matrix (make-instance &#039;matrix-element))
        (col-array (make-array (* 4 9 9)))
        (row-array (make-array (* 9 9 9))))
    (add-constraint-headers matrix &quot;Row&quot; &quot;Col&quot;)
    (add-constraint-headers matrix &quot;Row&quot; &quot;Number&quot;)      
    (add-constraint-headers matrix &quot;Col&quot; &quot;Number&quot;)      
    (add-constraint-headers matrix &quot;Block&quot; &quot;Number&quot;)
    (loop with foo = (right matrix)
          for i from 0
          until (eql foo matrix)
          do (setf (aref col-array i) foo
                   foo (right foo)))
    (rcv-loop
     (let* ((triplet (list r c v))
            (r-c (make-instance &#039;column-element
                                :column-header (aref col-array (+ (* 9 r)
                                                                  c))
                                :triplet triplet))
            (r-v (make-instance &#039;column-element
                                :column-header (aref col-array (+ (* 9 9)
                                                                  (* 9 r)
                                                                  v))
                                :triplet triplet))
            (c-v (make-instance &#039;column-element
                                :column-header (aref col-array (+ (* 2 9 9)
                                                                  (* 9 c)
                                                                  v))
                                :triplet triplet))
            (b-v (make-instance &#039;column-element
                                :column-header (aref col-array (+ (* 3 9 9)
                                                                  (* 9 (+ (* 3 (floor r 3))
                                                                          (floor c 3)))
                                                                  v))
                                :triplet triplet)))
       (insert-rightof r-c r-v)
       (insert-rightof r-v c-v)
       (insert-rightof c-v b-v)
       (setf (aref row-array (+ (* 9 (+ (* 9 r) c)) v)) r-c)))
    (values matrix row-array)))

&lt;/pre&gt;
&lt;p&gt;

Ok, this is the big one. I first create the row of header elements,
adding a short descriptive name in each element. I collect them in 
a array as well, so it is easy to reference the headers when adding
the elements later.
&lt;/p&gt;
&lt;p&gt;
Each row in the matrix has 4 elements. One for the row/col constraint,
one for row/value, one for col/value and one for block/value. Remember that
the make-instance method for column-elements automatically inserts the 
element in the right column if I pass it a :column-header argument.
&lt;/p&gt;
&lt;p&gt;
Finally I arrange the elements in a row and put a pointer to the row in my
row-array.
&lt;/p&gt;

&lt;pre&gt;

(defun cover-col (col-header)
  (do ((elem (down col-header) (down elem)))
      ((eql elem col-header) col-header)
    (do ((row-elem (right elem) (right row-elem)))
        ((eql row-elem elem) row-elem)
      (remove-vertical row-elem)))
  (remove-horizontal col-header))

&lt;/pre&gt;
&lt;p&gt;

Knuth calls the hiding of columns/rows for covering, so I&#039;m going to
use the same name. This function takes a column header, and for each
row that thas an element in this column, it will hide the row vertically
so that this row can not be chosen later. So if col-header is the header
of the first column, this will remove all rows with a element in the
first column.

&lt;/p&gt;
&lt;pre&gt;
(defun uncover-col (col-header)
  (do ((elem (up col-header) (up elem)))
      ((eql elem col-header) col-header)
    (do ((row-elem (right elem) (right row-elem)))
        ((eql row-elem elem) row-elem)
      (replace-vertical row-elem)))
  (replace-horizontal col-header))

&lt;/pre&gt;
&lt;p&gt;

Uncovering the column again. Both this and the previous function test 
for the equality of the current and initial element to detect that the
circular list has been traversed.

&lt;/p&gt;
&lt;pre&gt;

(defun cover-row (elem)
  (do ((column-iter (right elem) (right column-iter)))
      ((eql elem column-iter))
    (cover-col (column-header column-iter))))

(defun uncover-row (elem)
  (do ((column-iter (left elem) (left column-iter)))
      ((eql elem column-iter))
    (uncover-col (column-header column-iter))))

&lt;/pre&gt;
&lt;p&gt;

When we choose a move we need to remove the colliding moves for all the
columns where the row have elements. This functions takes care of this 
by iterating over the row, and calling cover-col for each of the columns.

&lt;/p&gt;
&lt;pre&gt;


(defun try-elem (elem array solution)
  (push elem solution)
  (cover-row elem)
  (let ((foo (find-solution array solution)))
    (uncover-row elem)
    (pop solution)
    foo))

&lt;/pre&gt;
&lt;p&gt;

Why the let? I want to return the value returned by find-solution to the caller
because the return value signals whether a solution has been found.

&lt;/p&gt;
&lt;pre&gt;

(defun find-smallest-col (array)
  (do ((head-iter (right array) (right head-iter))
       (cur-min (right array) (if (&lt; (size head-iter) (size cur-min))
                                head-iter
                                cur-min)))
      ((or (= 1 (size cur-min))
           (eql head-iter array)) cur-min)))

&lt;/pre&gt;
&lt;p&gt;

Loop through the headers and find the column with the smallest number
of elements. If we find a column with only one element, we can stop
searching.

&lt;/p&gt;
&lt;pre&gt;

(defun find-solution (array solution)
  (if (eql (left array) array)
    (progn
      (print-solution solution)
      t)
    (let ((col-header (find-smallest-col array)))
      (prog2
          (cover-col col-header)
          (do ((row-elem (down col-header) (down row-elem)))      
              ((or (eql row-elem col-header)
                   (try-elem row-elem array solution))
               (not (eql row-elem col-header))))
        (uncover-col col-header)))))

&lt;/pre&gt;
&lt;p&gt;

Try to find a solution. If all the headers are hidden, we have found
a solution, and can print it out. Return t to signal that the solution
is found. If a solution is not found yet, find the column with the
smallest number of elements and try out each element to see if we find
a solution. If a solution is found try-elem will return true, and we 
can stop searching. Make sure to pass on the true value to the calling
function.

&lt;/p&gt;
&lt;pre&gt;

(let ((solc 0))
  (defun print-solution (solution)
    (format t &quot;  ~a  &quot; (incf solc))
    (loop with arr = (make-array &#039;(9 9))
          for s in solution
          do (destructuring-bind (i j d) (triplet s)
               (setf (aref arr i j) (+ 1 d)))
          finally (loop for i from 0 to 8
                        do (format t &quot;~{~A~}&quot;
                                   (loop for j from 0 to 8
                                         collect (aref arr i j))))))
  
  (defun reset-count ()
    (setf solc 0)))

&lt;/pre&gt;
&lt;p&gt;

Very simple way of printing out solutions. I just build up the
resulting matrix from the triplets in the solution list and then print
out the resulting matrix on a single line. I also maintain a counter
that I can reset counting how many puzzles has been solved. 

&lt;/p&gt;
&lt;pre&gt;

(defun read-starting-position (pos-string)
  (with-input-from-string (s pos-string)
    (remove-if &#039;null
               (apply &#039;append
                      (loop for r from 0 to 8
                            collect (loop for c from 0 to 8
                                          collect (let ((v (- (char-code (read-char s))
                                                              (char-code #\0))))
                                                    (when (&gt; v 0)
                                                      (list r c (1- v))))))))))

&lt;/pre&gt;
&lt;p&gt;

Our starting positions is just a string of numbers where 0 means an open square. 
This function collects a list of triplets (r c v) for all non-null positions.
Note the complete lack of any validation of input. I have to subtract 1 from the
value because I use the value as a index into the matrix and indexes start at 0.

&lt;/p&gt;
&lt;pre&gt;

(defun solve-file (filename)
  (reset-count)
  (multiple-value-bind (matrix rowarr) (sudoinit)
    (with-open-file (s filename)
      (do ((string (read-line s nil &#039;eof) (read-line s nil &#039;eof)))
          ((eql string &#039;eof) nil)
	(format t &quot;~%~a&quot; string)
        (solve string matrix rowarr)))))

(defun solve (pos-string &amp;optional matrix rowarr)
  (unless (and matrix rowarr)
    (multiple-value-bind (foo bar) (sudoinit)
      (setf matrix foo)
      (setf rowarr bar)))
  (let ((solution ()))
    (dolist (triplet (read-starting-position pos-string))
      (destructuring-bind (i j d) triplet
        (push (aref rowarr (+ (* 9 (+ (* 9 i) j)) d)) solution)
        (cover-col (column-header (aref rowarr (+ (* 9 (+ (* 9 i) j)) d))))
        (cover-row (aref rowarr (+ (* 9 (+ (* 9 i) j)) d)))))
    (find-solution matrix solution)
    (do ((elem (pop solution) (pop solution)))
        ((null elem) matrix)
      (uncover-row elem)
      (uncover-col (column-header elem)))))

&lt;/pre&gt;
&lt;p&gt;

Finally, getting to run the whole thing. &lt;code&gt;solve-file&lt;/code&gt; just
reads in a file a line at a time and passes it on to the solve funtion
for processing. I create the matrix and the row-array in solve-file as 
well, otherwise I would have to recreate the matrix for every puzzle.

&lt;/p&gt;
&lt;p&gt;

The solve function is quite simple, read in the starting position. apply
the moves in the starting position as if it is moves we have searched so 
far. Pass everything on to find-solution, and clean up the matrix for 
reuse after find-solution returns.

&lt;/p&gt;
&lt;p&gt;

So how good is it? Remember a long time ago, I said something about
the number of possibilities being a very large number? On my machine,
which is a good but not top of the line machine, this program manages
to solve about 200 puzzles/second. And that is without doing much in
the way of optimizing.

&lt;/p&gt;
&lt;p&gt;
As usual: Feedback welcome at &lt;a href=&quot;mailto:asbjxrn@bjxrnstad.net&quot;&gt;asbjxrn@bjxrnstad.net&lt;/a&gt;
&lt;/p&gt;
</description>
    </item>
    <item>
      <title>The blog</title>
      <link>http://www.jalat.com/blogs/lisp?id=3</link>
      <pubDate>Mon, 10 Jan 2006 09:35:06 GMT</pubDate>
      <description>&lt;p&gt;

I want to make a blog framework. Because, if there is one thing the
world needs these days, it&#039;s another blog framework. I also couldn&#039;t
find much example code around for &lt;a
href=&quot;http://weitz.de/tbnl&quot;&gt;TBNL&lt;/a&gt;, a web framework by Edi Weitz
which I&#039;ve been looking at looking at. (I didn&#039;t search that hard 
for examples, and quite a bit of the code below is from examples
I found after starting to write this.) Anyway, I figured I&#039;ll just make
some example code myself and keep it around in case I need it later.

&lt;/p&gt;
&lt;p&gt;

Bill Clementson has &lt;a
href=&quot;http://bc.tech.coop/blog/041111.html&quot;&gt;written&lt;/a&gt; about getting
TBNL up and running with apache and mod_lisp. In this example I&#039;m
going to use &lt;a href=&quot;http://weitz.de/hunchentoot/&quot;&gt;hunchentoot&lt;/a&gt;, a
pure lisp web server by (again) Edi Weitz.

&lt;/p&gt;
&lt;p&gt;

After reading the the third chapter of &lt;a
href=&quot;http://www.gigamonkeys.com/book/practical-a-simple-database.html&quot;&gt;
Practical common lisp&lt;/a&gt; by Peter Seibel we choose to use simple
lists to store data about the blog, because ripping off code is way
easier than writing our own. We&#039;ll keep individual entries in separate
files so writing and editing them can be done with whatever tools we
want to use.

&lt;/p&gt;
&lt;p&gt;

Let&#039;s get started:

&lt;/p&gt;
&lt;pre&gt;

(defparameter *blog-db-item-dir* &quot;/home/asbjxrn/blog/items/&quot;)
(defparameter *blog-db-file* &quot;/home/asbjxrn/blog/blog-db&quot;)
(defparameter *blog-db* ())

(defun create-blog (&amp;key id title description author)
  &quot;Create a new blog by pushing a list containg a blog description onto the blog database.
Return the updated blog-database.&quot;
  (let ((new-blog (list
                   :id id
                   :title title
                   :description description
                   :author author
                   :items ())))
    (push new-blog *blog-db*)
    new-blog))

&lt;/pre&gt;
&lt;p&gt;

As you can see, I&#039;ve made room for growth. &lt;code&gt;*blog-db*&lt;/code&gt; is a
list of blogs. This means we need some functions to find/list/delete
the blogs. The print functions I only used for debugging/testing of the 
blog framework. 

&lt;/p&gt;
&lt;pre&gt;

(defparameter *blog-hosts-prefix* &quot;http://www.jalat.com&quot;)
(defparameter *blog-script-name-prefix* &quot;/blogs/&quot;)

(defun print-blog-headers (blog)
  &quot;Prints out everything but the items of a blog.&quot;
  (format t &quot;Name: ~a~%Title: ~a~%Description: ~a~%Homepage: ~a~%Author: ~a~%~%&quot;
          (getf blog :id)
          (getf blog :title)
          (getf blog :description)
          (getf blog :author)))

(defun print-blogs ()
  &quot;Prints out the name, title, homepage, descripton and author of all the registered blogs&quot;
  (loop for blog in *blog-db*
        do (print-blog-headers blog)))

(defun homepage (blog)
  &quot;Generates the homepage uri for the blog&quot;
  (format nil &quot;~a~a~a&quot; *blog-hosts-prefix* *blog-script-name-prefix*
          (getf blog :id)))
                 
(defun get-blog (name)
  &quot;Returns the blog identified by \&quot;name\&quot;&quot;
  (when (stringp name)
    (find-if #&#039;(lambda (x) (string= name (getf x :id)))
             *blog-db*)))

(defun delete-blog (name)
  &quot;Deletes the blog identified by \&quot;name\&quot;. Destructive on *blog-db*&quot;
  (when (stringp name)
    (setf *blog-db*
          (remove-if #&#039;(lambda (x) (string= name (getf x :id)))
                     *blog-db*))))

&lt;/pre&gt;
&lt;p&gt;

So far so good, time to add some functions for handling the items in each blog.
since values passed to us through a get or post are strings, I parse the id
arguments if they are strings:

&lt;/p&gt;
&lt;pre&gt;

(defun max-blog-id (blog)
  &quot;Find the highest id of any item in a blog.&quot;
  (if (getf blog :items)
    (apply #&#039;max (loop for entry in (getf blog :items)
                       collect (getf entry :id)))
    0))

(defun add-blog-item (blog &amp;key title file description)
  &quot;Add a new item in a blog.&quot;
  (push
   (list :title title
         :file file
         :description description
         :pub-time (get-universal-time)
         :id (+ 1 (max-blog-id blog)))
   (getf blog :items)))

(defun delete-blog-item (blog id)
  &quot;Deletes a item in a blog. Destructive on the blog&quot;
  (if (stringp id)
    (setf id (parse-integer id :junk-allowed t)))
  (setf (getf blog :items)
        (remove-if #&#039;(lambda (x) (eql id (getf x :id)))
                   (getf blog :items))))

(defun get-blog-item (blog id)
  &quot;Find blog item with id id.&quot;
  (if (stringp id)
    (setf id (parse-integer id :junk-allowed t)))
  (find-if #&#039;(lambda (x) (eql id (getf x :id)))
           (getf blog :items)))

(defun get-last-blog-item (blog)
  &quot;Return the last item for a blog&quot;
  (get-blog-item blog (max-blog-id blog)))

(defun list-blog-items (blog)
  &quot;Print a list of items in a blog.&quot;
  (format t &quot;~{~{~a:~t~a~%~}~%~}&quot; (getf blog :items)))

&lt;/pre&gt;
&lt;p&gt;

A couple of functions to store and load our data from disk:

&lt;/p&gt;
&lt;pre&gt;

(defun save-blog-db ()
  &quot;Simply write out the blog structure to the db file.&quot;
  (with-open-file (out *blog-db-file*
                       :direction :output
                       :if-exists :supersede)
    (with-standard-io-syntax
      (print *blog-db* out))))

(defun load-blog-db ()
  &quot;Simple read in the whole db in one operation.&quot;
  (with-open-file (in *blog-db-file*)
    (with-standard-io-syntax
      (setf *blog-db* (read in)))))

&lt;/pre&gt;
&lt;p&gt;

And some functions to read the blog entries from disk. To improve performance
one might want to keep everything in memory, but I don&#039;t think that is going
to be an issue. Besides, it&#039;s convenient to be able to just edit the files 
themselvesm, and have the blog update automatically.

&lt;/p&gt;
&lt;pre&gt;

(defun slurp-file (filename)
  &quot;Dump the contents of a file into a string.&quot;
  (with-open-file (stream filename)
    (let ((seq (make-string (file-length stream))))
      (read-sequence seq stream)
      seq)))

(defun get-blog-file (blog id)
  &quot;Reads the file of a blog item and returns it as a string.&quot;
  (let* ((item (get-blog-item blog id))
         (filename (concatenate &#039;string *blog-db-item-dir* (getf item :file))))
    (slurp-file filename)))

&lt;/pre&gt;
&lt;p&gt;

I think I&#039;m done with the backend. Time to start with TBNL. First some
convenience functions to start and stop the server. In the start
function I also set up my dispatch-table:
&lt;ul style=&quot;padding: 0.5em;&quot;&gt;
&lt;li&gt; &lt;code&gt;/blogs/&amp;lt;foo&amp;gt;&lt;/code&gt; is handled by the function &lt;code&gt;blog-page&lt;/code&gt; &lt;/li&gt;
&lt;li&gt; &lt;code&gt;/admin&lt;/code&gt; is handled by the function &lt;code&gt;manage-blogs&lt;/code&gt; &lt;/li&gt;
&lt;li&gt; A folder dispatcher serves all files in my static-files directory &lt;/li&gt;
&lt;li&gt; And I have a separate static file dispatcher that handles &quot;/favicon.ico&quot;, generously stolen from planet.lisp.org.&lt;/li&gt;
&lt;/ul
&lt;/p&gt;
&lt;p&gt;

Btw. These functions are Hunchentoot specific, use start-tbnl if you
use mod_lisp, araneida or something else.

&lt;/p&gt;
&lt;pre&gt;

(defparameter *blog-script-name-prefix* &quot;/blogs/&quot;)
(defparameter *blog-admin-uri* &quot;/admin&quot;)
(defparameter *blog-static-uri* &quot;/static-files/&quot;)
(defparameter *blog-static-dir* &quot;/home/asbjxrn/blog/static-files/&quot;)
(defparameter *blog-server* nil)
(defparameter *log-file* &quot;/home/asbjxrn/blog/log&quot;)

(defun start-blog (&amp;key port)
  &quot;starts up the server, and initializes our dispatch-table&quot;
  (setf (log-file) (make-pathname :defaults *log-file*))
  (load-blog-db)
  (setq *blog-server*
        (tbnl:start-server :port port)
        *dispatch-table*
        (list (create-prefix-dispatcher *blog-script-name-prefix* &#039;blog-page)
              (create-prefix-dispatcher *blog-admin-uri* &#039;manage-blogs)              
              (create-folder-dispatcher-and-handler *blog-static-uri*
                                                    (make-pathname :defaults *blog-static-dir*))
              (create-static-file-dispatcher-and-handler &quot;/favicon.ico&quot;
                                                         (merge-pathnames
                                                          (make-pathname :defaults *blog-static-dir*)
                                                          &quot;favicon.ico&quot;))
              (create-prefix-dispatcher &quot;/index.html&quot; &#039;front-page)                            
              (create-prefix-dispatcher &quot;/the-blog.html&quot; &#039;manage-blogs)              
              &#039;default-dispatcher)))

(defun stop-blog ()
  (tbnl:stop-server *blog-server*))

&lt;/pre&gt;
&lt;p&gt;

All blogs are handled by the same function which will use
&lt;code&gt;request-uri&lt;/code&gt; to get hold of the name of the blog the user
wants to read. So I need a function that gets hold of the name by
removing the &lt;code&gt;/blogs/&lt;/code&gt; part of the uri.&lt;br/&gt;
At the same time, I&#039;ll make a function that prints out a timestamp
in a readable way. (Totally ignoring things like timezones etc.)

&lt;/p&gt;
&lt;pre&gt;

(defun remove-prefix (uri prefix)
  &quot;Returns the prefix from an uri in search of a blog name. 
Big assumtion: Blog names consists only of latin characters.&quot;
  (let ((scanstring (concatenate &#039;string prefix &quot;([A-Za-z]+)&quot;)))
    (multiple-value-bind (dummy matchvector) (cl-ppcre:scan-to-strings scanstring uri)
      (declare (ignore dummy))
      (if matchvector
        (svref matchvector 0)
        &quot;&quot;))))

(defun timestring (timestamp)
  &quot;Takes a timestamp and returns a string formatted with year-month-day hour:minutes&quot;
  (multiple-value-bind (sec min hour day mnt year weekday dst tz)
      (decode-universal-time timestamp)
    (declare (ignore sec weekday dst tz))
    (format nil &quot;~d-~d-~d ~2,&#039;0d:~2,&#039;0d&quot; year mnt day hour min)))

&lt;/pre&gt;
&lt;p&gt;

HTML coming up. At long last some HTML generation. I&#039;m going to use
the &lt;a href=&quot;http://weitz.de/cl-who&quot;&gt;CL-WHO&lt;/a&gt; library written by Edi Weitz
to generate the HTML, but you can use whatever you want as long as your
handler functions returns strings containing HTML. One nice thing about
this approac is that you can just call the functions from the REPL and
see if you get the HTML you expect. Use &lt;code&gt;:indent t&lt;/code&gt; to make
it easier to read.

&lt;/p&gt;
&lt;p&gt;

The first function is a function I&#039;ll use to make a navigation bar. It
takes a list of items, and generates a list of anchor tags, where the 
title of the item is used as the text of the link and the id of the item
is used to create a uri like &quot;?id=5&quot;. So these uris will only point back
to the same page, but I&#039;ll use the parameter to decide what to display.

&lt;/p&gt;
&lt;pre&gt;

(defun navigate-items (items)
  &quot;Returns html code four our navigation sidebar.&quot;
  (with-html-output-to-string (*standard-output* nil :indent t)
    (:ul
     (loop for item in items
           do (htm
               (:li
                (:a :href (format nil &quot;?id=~a&quot; (getf item :id))
                 (fmt &quot;~a&quot; (getf item :title)))
                (:br)
                (when (getf item :pub-time)
                  (htm (fmt &quot;~a&quot; (timestring (getf item :pub-time)))
                       (:br)))))))))

&lt;/pre&gt;
&lt;p&gt;

Finally the function that displays the blog item.&lt;br/&gt; 

First I use &lt;code&gt;script-name&lt;/code&gt; and &lt;code&gt;remove-prefix&lt;/code&gt; 
to get the name of the blog, returning a 404 if the blog doesn&#039;t exist.&lt;br/&gt;

Then I use &lt;code&gt;(get-parameter &quot;id&quot;)&lt;/code&gt; to get the
&lt;code&gt;?id=..&lt;/code&gt; part of the uri if it exists. If it doesn&#039;t exist
or no item with the specified id exist, I just show the latest item
for this blog.

&lt;/p&gt;
&lt;p&gt;

The page is split up in three parts, a header, the content, and a navigation
bar.

&lt;/p&gt;
&lt;pre&gt;

(defparameter *blog-css-file* &quot;/static-files/stylesheet.css&quot;)

(defun blog-page ()
  &quot;Finally, the function that writes the html for our blog output.&quot;
  (let ((blog (get-blog (remove-prefix (script-name) *blog-script-name-prefix*))))
    (unless blog
      (setf (return-code *reply*)
            +http-not-found+)
      (return-from blog-page))
    (let* ((item-id (or (and (get-parameter &quot;id&quot;)
                             (parse-integer (get-parameter &quot;id&quot;)))
                        (max-blog-id blog)))
           (item    (get-blog-item blog item-id)))
      (unless item
        (redirect (format nil &quot;~a?id=~a&quot; (script-name) (max-blog-id blog)))
        (return-from blog-page))
      (with-html-output-to-string (*standard-output* nil :prologue t :indent t)
        (:html
         (:head
          (:title (fmt (concatenate &#039;string (getf blog :title) &quot; - &quot; (getf item :title))))
          (:link :href *blog-css-file* :rel &quot;stylesheet&quot; :type &quot;text/css&quot;))
         (:body
          (:div :id &quot;Header&quot;
           (:h1 (:a :href (getf blog :homepage)
                 (fmt &quot;~a&quot; (getf blog :title)))))
          (:div :id &quot;Content&quot;
           (:h3 (fmt &quot;~a&quot; (getf item :title)))
           (:p (fmt &quot;~a&quot; (get-blog-file blog (getf item :id)))))
          (:div :id &quot;Menu&quot;
           (:h4 &quot;Blogged:&quot;)
           (fmt &quot;~a&quot; (navigate-items (getf blog :items))))))))))

&lt;/pre&gt;
&lt;p&gt;

And that&#039;s it. Get hold of some css, stuff it in /static-files/ and
you should have a working website where people can go to read your
latest musings.  Of course, updating is a bit inconvenient as you have
to execute commands create-blog/add-blog-item/etc. at the REPL. A simple
form where one could maintain the data would me a lot more convenient...

&lt;/p&gt;
&lt;p&gt;

It could look something like this:

&lt;/p&gt;
&lt;pre&gt;

(defun blog-form (blog)
  &quot;A form with blog data.&quot;
  (with-html-output-to-string (*standard-output* nil :indent t)
    (:h3 (:a :href (homepage blog)
          (fmt &quot;~a&quot; (or (getf blog :title) &quot;&quot;))))
    (:h5 (fmt &quot;~a&quot; (or (getf blog :description) &quot;&quot;)))
    (:form :method :post 
     (:table 
      (:tr
       (:td &quot;Title: &quot;)
       (:td
        (:input :type :text
         :name &quot;new-blog-title&quot;
         :value (or (getf blog :title) &quot;&quot;))))
      (:tr
       (:td &quot;Description: &quot;)
       (:td
        (:input :type :text
         :name &quot;new-blog-description&quot;
         :value (or (getf blog :description) &quot;&quot;))))
      (:tr
       (:td &quot;Homepage: &quot;)
       (:td (fmt &quot;~a~a&quot; *blog-hosts-prefix* *blog-script-name-prefix*)
        (:input :type :text
         :name &quot;new-blog-id&quot;
         :value (or (getf blog :id) &quot;&quot;))))
      (:tr
       (:td &quot;Author: &quot;)
       (:td
        (:input :type :text
         :name &quot;new-blog-author&quot;
         :value (or (getf blog :author) &quot;&quot;))))
      (:tr
       (:td (:input :type :submit :name &quot;delete-blog&quot; :value &quot;Delete blog&quot;))
       (:td (:input :type :submit :name &quot;update-blog&quot; :value &quot;Update blog&quot;)))))))

&lt;/pre&gt;
&lt;p&gt;

Not particulary pretty, but this is not for public consumption, so I don&#039;t care.
To apply the changes we make in the form, I&#039;ll call this function:

&lt;/p&gt;
&lt;pre&gt;

(defun update-blog (blog)
  &quot;parses the post parameters and updates the blog accordingly&quot;
  (let ((post-parameter-p)
        (new-blog (or blog ())))
    (when (post-parameter &quot;new-blog-title&quot;)
      (setf (getf new-blog :title) (post-parameter &quot;new-blog-title&quot;))
      (setq post-parameter-p t))
    (when (post-parameter &quot;new-blog-description&quot;)
      (setf (getf new-blog :description) (post-parameter &quot;new-blog-description&quot;))
      (setq post-parameter-p t))
    (when (post-parameter &quot;new-blog-id&quot;)
      (setf (getf new-blog :id) (post-parameter &quot;new-blog-id&quot;))
      (setq post-parameter-p t))
    (when (post-parameter &quot;new-blog-author&quot;)
      (setf (getf new-blog :author) (post-parameter &quot;new-blog-author&quot;))
      (setq post-parameter-p t))
    (when post-parameter-p
      (unless blog
        (setf blog (apply &#039;create-blog new-blog)))
      (save-blog-db)))
  blog)

&lt;/pre&gt;
&lt;p&gt;

And similar functions for items within the blog, and a function that loops
through the items in a blog and makes a form for each one:

&lt;/p&gt;
&lt;pre&gt;

(defun item-form (item)
  &quot;A simple one-line form for a blog item&quot;
  (with-html-output-to-string (*standard-output* nil)
    (:form :method :post 
    (:input :type :hidden :name &quot;item-id&quot; :value (getf item :id))
     (:tr
      (:td
       (:input :type :text
        :name &quot;new-item-title&quot;
        :value (or (getf item :title) &quot;&quot;)))
      (:td
       (:input :type :text
        :name &quot;new-item-description&quot;
        :value (or (getf item :description) &quot;&quot;)))
      (:td
       (:input :type :text
        :name &quot;new-item-file&quot;
        :value (or (getf item :file) &quot;&quot;)))
      (:td (:input :type :submit :name &quot;update-item&quot; :value (if item &quot;Update item&quot; &quot;Save item&quot;)))
      (when item
        (htm (:td (:input :type :submit :name &quot;delete-item&quot; :value &quot;Delete item&quot;))))))))

(defun update-item (blog)
  &quot;Updates an item in a blog.&quot;
  (let ((post-parameter-p)
        (new-item (or (get-blog-item blog (post-parameter &quot;item-id&quot;))
                      ())))
    (when (post-parameter &quot;new-item-title&quot;)
      (setf (getf new-item :title) (post-parameter &quot;new-item-title&quot;))
      (setq post-parameter-p t))
    (when (post-parameter &quot;new-item-description&quot;)
      (setf (getf new-item :description) (post-parameter &quot;new-item-description&quot;))
      (setq post-parameter-p t))
    (when (post-parameter &quot;new-item-file&quot;)
      (setf (getf new-item :file) (post-parameter &quot;new-item-file&quot;))
      (setq post-parameter-p t))
    (when post-parameter-p
      (unless (get-blog-item blog (getf new-item :id))
        (apply &#039;add-blog-item blog new-item)))
    (when post-parameter-p
      (save-blog-db))))


(defun blog-items-forms (blog)
  &quot;makes a list of forms, one for each item in the blog&quot;
  (with-html-output-to-string (*standard-output* nil :indent t)
    (:table 
     (:tr
      (:th &quot;Title&quot;) (:th &quot;Description&quot;) (:th &quot;File&quot;))
     (fmt (item-form nil))
     (loop for item in (getf blog :items)
           do (fmt (item-form item))))))

&lt;/pre&gt;
&lt;p&gt;

The observant reader will have noticed that there are delete-buttons
in the forms that are not handled by the above functions. I&#039;m going to
do that in this function that will be the central calling point from 
our admin-page:

&lt;/p&gt;
&lt;pre&gt;

(defun handle-update (blog)
  &quot;apply changes to blog based on post parameters in the request&quot;
  (cond
   ((post-parameter &quot;delete-blog&quot;) (progn (delete-blog (getf blog :id))
                                     (redirect (format nil &quot;~a?id=~a&quot; (script-name)))))
   ((post-parameter &quot;delete-item&quot;) (delete-blog-item blog (post-parameter &quot;item-id&quot;)))
   ((post-parameter &quot;update-blog&quot;) (update-blog blog))
   ((post-parameter &quot;update-item&quot;) (update-item blog)))
  (redirect (format nil &quot;~a&quot; (request-uri))))

&lt;/pre&gt;
&lt;p&gt;

Finally the blog admin page. The only new thing here is that we put in
some authorization control to prevent just anyone to connect and mess
up our data.

&lt;/p&gt;
&lt;pre&gt;

(defun manage-blogs ()
  &quot;Let the user manage his blogs&quot;
  (multiple-value-bind (user password)
      (authorization)
    (cond ((or (string/= user &quot;admin&quot;)
               (string/= password &quot;admin&quot;))    ; Noone will guess this.
           (require-authorization))
          (t
           (let ((blog (get-blog (get-parameter &quot;id&quot;))))
             (when (post-parameters)
               (handle-update blog))
             (with-html-output-to-string (*standard-output* nil :prologue t :indent t)
               (:html
                (:head
                 (:title (fmt (concatenate &#039;string
                                           (getf blog :title)
                                           &quot; - admin - &quot;
                                           (or (getf blog :title) &quot;&quot;))))
                 (:link :href *blog-css-file* :rel &quot;stylesheet&quot; :type &quot;text/css&quot;))
                (:body
                 (:div :id &quot;Header&quot;
                  (:h1 (fmt &quot;Admin - ~a&quot; (or (getf blog :title) &quot;&quot;))))
                 (:div :id &quot;Content&quot;
                  (fmt &quot;~a&quot; (blog-form blog))
                  (fmt &quot;~a&quot; (blog-items-forms blog)))
                 (:div :id &quot;Menu&quot;
                  (:a :href  (format nil &quot;~a?id=&quot; (script-name))
                   &quot;New blog&quot;)
                  (:h4 &quot;Blogs:&quot;)
                  (fmt &quot;~a&quot; (navigate-items *blog-db*)))))))))))

&lt;/pre&gt;
&lt;p&gt;

That is about it. There is also a dispatcher set up for
&lt;code&gt;index.html&lt;/code&gt; but you should be able to put something
together yourself now and this write-up has become far longer than I
was planning to make it. Other exercises for the reader are: generating rss
feeds, file upload though the form, comments, etc.

&lt;/p&gt;
&lt;p&gt;
As usual: Feedback welcome at &lt;a href=&quot;mailto:asbjxrn@bjxrnstad.net&quot;&gt;asbjxrn@bjxrnstad.net&lt;/a&gt;
&lt;/p&gt;



</description>
    </item>
    <item>
      <title>Back of the envelope</title>
      <link>http://www.jalat.com/blogs/lisp?id=2</link>
      <pubDate>Mon, 10 Jan 2006 09:34:35 GMT</pubDate>
      <description>&lt;h3&gt;Playing with the REPL for fun and profit. (yeah, you wish)&lt;/h3&gt;
&lt;p&gt;

In my &lt;a href=&quot;http://www.jalat.com/the-game.html&quot;&gt;previous write-up&lt;/a&gt; I
claimed that with a set of moves an end position could be reached from
any start position. In fact, any position can be reached from any other
position. How can I be so sure?

&lt;/p&gt;
&lt;p&gt;

This time I&#039;m not going to write a program. Well, in a sense I do, but
I&#039;m just going to type in expressions at the lisp REPL, and see where
I end up. This time I&#039;m not really bothered by effiency or elegance of
the code, I&#039;m more concerned about giving a feel for this kind of
back-of-the-envelope coding you can do withing the REPL.  You will
also see that I kind of repeat the same code again and again with
small modifications until I get it right. Because of this I feel it&#039;s
important to use lisp with good history editing functions or a
interface like the excellent &lt;a
href=&quot;http://common-lisp.net/project/slime/&quot;&gt;slime&lt;/a&gt; mode for emacs.

&lt;/p&gt;
&lt;p&gt;

And BTW: From the history numbers, you can tell that I actually messed
around a lot more than what I&#039;m showing you. This is normal and
not an indication of my cluelessness level. I think.

&lt;/p&gt;
&lt;p&gt;

With that out of the way, let&#039;s get started. First, let&#039;s recreate the
apply-move function, this time we want to combine any kind of
moves, not just the predefined moves in the *moves* list:

&lt;/p&gt;
&lt;pre&gt;

FLIPPER 50 &gt; (defun xor (a b)
               (loop for ap in a
                     for bp in b
                     collect (mod (+ ap bp) 2)))
XOR

FLIPPER 51 &gt; (xor &#039;(1 0 1) &#039;(1 1 0))
(0 1 1)

FLIPPER 52 &gt; (xor &#039;(1 0 1) &#039;(0 1 1))
(1 1 0)

&lt;/pre&gt;
&lt;p&gt;

If you played around with the game, you already knew this, but if you
look at what we just did you can see that by applying a move on the
result of a move, we get back to the starting position. What this
means for us, is that we can replace a move in our list with the
result of applying another move on it and we will still be able to
generate the same results.

&lt;/p&gt;
&lt;p&gt;
Let&#039;s look at our moves again (and add a move identifier to each move):
&lt;/p&gt;
&lt;pre&gt;

FLIPPER 55 &gt; (defparameter *c-moves* (loop for m in *moves*
                                           for i upfrom 1
                                           collect (cons m (list i))))
*C-MOVES*

FLIPPER 56 &gt;  (format t &quot;~{~a~%~}&quot; *c-moves*)
((1 1 0 1 1 0 0 0 0) 1)
((1 1 1 0 0 0 0 0 0) 2)
((0 1 1 0 1 1 0 0 0) 3)
((1 0 0 1 0 0 1 0 0) 4)
((1 0 1 0 1 0 1 0 1) 5)
((0 0 1 0 0 1 0 0 1) 6)
((0 0 0 1 1 0 1 1 0) 7)
((0 0 0 0 0 0 1 1 1) 8)
((0 0 0 0 1 1 0 1 1) 9)
NIL
&lt;/pre&gt;
&lt;p&gt;

Not quite what I had in mind, we want the move identifier to be a list
so we can push other identifiers onto it when we combine moves.

&lt;pre&gt;
FLIPPER 57 &gt; (defparameter *c-moves* (loop for m in *moves*
                                           for i upfrom 1
                                           collect (list m (list i))))
*C-MOVES*

FLIPPER 58 &gt;  (format t &quot;~{~a~%~}&quot; *c-moves*)
((1 1 0 1 1 0 0 0 0) (1))
((1 1 1 0 0 0 0 0 0) (2))
((0 1 1 0 1 1 0 0 0) (3))
((1 0 0 1 0 0 1 0 0) (4))
((1 0 1 0 1 0 1 0 1) (5))
((0 0 1 0 0 1 0 0 1) (6))
((0 0 0 1 1 0 1 1 0) (7))
((0 0 0 0 0 0 1 1 1) (8))
((0 0 0 0 1 1 0 1 1) (9))
NIL
&lt;/pre&gt;
&lt;p&gt;

Better. But our xor function won&#039;t work with &quot;moves&quot; from this list,
we need to add code to handle the move identifiers. We will append the
identifiers to keep track of which moves are combined to generate the
new move.

&lt;/p&gt;
&lt;pre&gt;

FLIPPER 59 &gt; (defun my-xor (a b)
               (list (xor (first a) (first b)) 
                     (append (second a) (second b))))
MY-XOR

FLIPPER 60 &gt; (my-xor (first *c-moves*) (second *c-moves*))
((0 0 1 1 1 0 0 0 0) (1 2))

&lt;/pre&gt;
&lt;p&gt;

Now, lets see if we can find a move with a specific &quot;bit&quot; set. (It&#039;s
not really a bit but an integer, but that&#039;s what I&#039;ll call it.) Let&#039;s
try to find the first move with the last bit set. (Should be move 5 by
looking at the table above.)

&lt;/p&gt;
&lt;p&gt;

We&#039;ll use the find-if function, find-if requires two arguments, a test
function and a list. The test function should accept one argument and
return true or false. We want to test if the nth element of the first
list of is equal to 1 and will use a lambda function for this. The
whole thing looks like this if we look for the 8th bit set:

&lt;/p&gt;
&lt;pre&gt;

FLIPPER 61 &gt; (find-if #&#039;(lambda (x) (= 1 (nth 8 (first x)))) 
                      *c-moves*)
((1 0 1 0 1 0 1 0 1) (5))

&lt;/pre&gt;
&lt;p&gt;

Ok, we&#039;re almost set, now we&#039;ll go through the list of moves, first looking
for a move with the first bit set, we will xor this move with all other moves 
with the first bit set. Then we&#039;ll do the same for the second bit, and so on.
First, let&#039;s try it out by just testing for the first bit and print it out:

&lt;/p&gt;
&lt;pre&gt;

FLIPPER 81 &gt; (let* ((bar (find-if #&#039;(lambda (x) (= 1 (nth 0 (first x)))) *c-moves*))
                    (gaz (remove bar *c-moves*)))
               (format t &quot;~{~a~%~}&quot;
                       (loop for move in gaz
                             collect (if (= 0 (nth 0 (first move)))
                                       move
                                       (my-xor bar move)))))
((0 0 1 1 1 0 0 0 0) (1 2))
((0 1 1 0 1 1 0 0 0) (3))
((0 1 0 0 1 0 1 0 0) (1 4))
((0 1 1 1 0 0 1 0 1) (1 5))
((0 0 1 0 0 1 0 0 1) (6))
((0 0 0 1 1 0 1 1 0) (7))
((0 0 0 0 0 0 1 1 1) (8))
((0 0 0 0 1 1 0 1 1) (9))
NIL

&lt;/pre&gt;
&lt;p&gt;

That almost worked, we forgot to put the first element back on. Let&#039;s add it back
in and at the same time wrap the whole thing in a loop that goes through the index for the &quot;bits&quot;.
We also have to make some changes inside the let* to update the bit index and the list of moves (foo).
Finally we&#039;ll print the result.
&lt;/p&gt;
&lt;pre&gt;

FLIPPER 88 &gt; (loop with foo = (copy-list *c-moves*)
                   for i from 0 to 8
                   do (let* ((bar (find-if #&#039;(lambda (x) (= 1 (nth i (first x)))) foo))
                             (gaz (remove bar foo)))
                        (setf foo 
                              (cons bar
                                    (loop for move in gaz
                                          collect (if (= 0 (nth i (first move)))
                                                    move
                                                    (my-xor bar move))))))
                   finally (format t &quot;~{~a~%~}&quot; foo))
((0 0 0 0 0 0 0 0 1) (1 2 1 2 1 1 4 1 2 1 2 1 2 1 1 5))
((1 0 1 1 0 0 0 1 0) (1 2 1 2 1 1 4 1 2 7))
((1 0 0 1 0 0 1 0 0) (1 2 1 2 1 1 4))
((1 0 1 1 0 1 0 0 0) (1 2 1 2 1 3))
((0 0 1 1 1 0 0 0 0) (1 2))
((1 1 1 0 0 0 0 0 0) (1 2 1))
((1 0 0 1 0 0 0 0 0) (1 2 1 2 1 1 4 1 2 1 2 1 2 1 1 5 1 2 1 2 1 3 1 2 1 2 6))
((0 0 1 0 0 0 0 0 0) (1 2 1 2 1 1 4 1 2 1 2 1 2 1 1 5 1 2 1 2 1 1 4 1 2 7 1 2 1 2 1 1 4 8))
((0 0 1 1 0 0 0 0 0) (1 2 1 2 1 1 4 1 2 1 2 1 2 1 1 5 1 2 1 2 1 1 4 1 2 7 1 2 1 2 1 3 1 2 9))
NIL

&lt;/pre&gt;
&lt;p&gt;

Huh? That doesn&#039;t look very nice at all. Let&#039;s try to print out the array for each loop and see what is going on.

&lt;/p&gt;
&lt;pre&gt;

FLIPPER 89 &gt; (loop with foo = (copy-list *c-moves*)
                   for i from 0 to 8
                   do (let* ((bar (find-if #&#039;(lambda (x) (= 1 (nth i (first x)))) foo))
                             (gaz (remove bar foo)))
                        (setf foo 
                              (cons bar
                                    (loop for move in gaz
                                          collect (if (= 0 (nth i (first move)))
                                                    move
                                                    (my-xor bar move)))))
                        (format t &quot;~{~a~%~}~%&quot; foo)))
((1 1 0 1 1 0 0 0 0) (1))
((0 0 1 1 1 0 0 0 0) (1 2))
((0 1 1 0 1 1 0 0 0) (3))
((0 1 0 0 1 0 1 0 0) (1 4))
((0 1 1 1 0 0 1 0 1) (1 5))
((0 0 1 0 0 1 0 0 1) (6))
((0 0 0 1 1 0 1 1 0) (7))
((0 0 0 0 0 0 1 1 1) (8))
((0 0 0 0 1 1 0 1 1) (9))

((1 1 0 1 1 0 0 0 0) (1))
((0 0 1 1 1 0 0 0 0) (1 2))
((1 0 1 1 0 1 0 0 0) (1 3))
((1 0 0 1 0 0 1 0 0) (1 1 4))
((1 0 1 0 1 0 1 0 1) (1 1 5))
((0 0 1 0 0 1 0 0 1) (6))
((0 0 0 1 1 0 1 1 0) (7))
((0 0 0 0 0 0 1 1 1) (8))
((0 0 0 0 1 1 0 1 1) (9))

[rest of output snipped.]
&lt;/pre&gt;
&lt;p&gt;

Duh, since the first move has the second bit as well as the first bit
set, it&#039;s chosen for the second round in the loop as well as the
first, and from then on everything is a mess. We want to choose new
moves a much as possible. Since find-if search from the front, we can
do that by putting &quot;bar&quot; at the end of the list after applying the xor
instead of the other way around.

&lt;/p&gt;
&lt;p&gt;

We can&#039;t just reorder the bar and the loop in the cons call since that
will break up &quot;bar&quot; the same way it broke the move identifier the
first time we tried to create the *c-moves* parameter. Read up on conses
and proper lists to figure out why.

&lt;/p&gt;
&lt;pre&gt;

FLIPPER 94 &gt; (loop with foo = (copy-list *c-moves*)
                   for i from 0 to 8
                   do (let* ((bar (find-if #&#039;(lambda (x) (= 1 (nth i (first x)))) foo))
                             (gaz (remove bar foo)))
                        (setf foo 
                              (append (loop for move in gaz
                                            collect (if (= 0 (nth i (first move)))
                                                      move
                                                      (my-xor bar move)))
                                      (list bar)))
                        (format t &quot;~{~a~%~}~%&quot; foo))
)
((0 0 1 1 1 0 0 0 0) (1 2))
((0 1 1 0 1 1 0 0 0) (3))
((0 1 0 0 1 0 1 0 0) (1 4))
((0 1 1 1 0 0 1 0 1) (1 5))
((0 0 1 0 0 1 0 0 1) (6))
((0 0 0 1 1 0 1 1 0) (7))
((0 0 0 0 0 0 1 1 1) (8))
((0 0 0 0 1 1 0 1 1) (9))
((1 1 0 1 1 0 0 0 0) (1))

((0 0 1 1 1 0 0 0 0) (1 2))
((0 0 1 0 0 1 1 0 0) (3 1 4))
((0 0 0 1 1 1 1 0 1) (3 1 5))
((0 0 1 0 0 1 0 0 1) (6))
((0 0 0 1 1 0 1 1 0) (7))
((0 0 0 0 0 0 1 1 1) (8))
((0 0 0 0 1 1 0 1 1) (9))
((1 0 1 1 0 1 0 0 0) (3 1))
((0 1 1 0 1 1 0 0 0) (3))

[more output snipped]

((1 0 0 0 0 0 0 0 0) (1 2 3 1 4 3 1 5 1 2 3 1 4 1 2 6 8 9 1 2 3 1))
((0 1 0 0 0 0 0 0 0) (1 2 3 1 4 1 2 6 1 2 3 1 4 7 9 1 2 3 1 4 1 2 3))
((0 0 1 0 0 0 0 0 0) (1 2 3 1 4 3 1 5 1 2 3 1 4 1 2 6 8 1 2 3 1 4 1 2 6 1 2 3 1 4 7 1 2 3 1 4 1 2))
((0 0 0 1 0 0 0 0 0) (1 2 3 1 4 1 2 6 8 1 2 3 1 4 1 2 6 9 1 2 3 1 4))
((0 0 0 0 1 0 0 0 0) (1 2 3 1 4 3 1 5 1 2 3 1 4 7 9))
((0 0 0 0 0 1 0 0 0) (1 2 3 1 4 1 2 6 8 1 2 3 1 4 7))
((0 0 0 0 0 0 1 0 0) (1 2 3 1 4 3 1 5 1 2 3 1 4 1 2 6))
((0 0 0 0 0 0 0 1 0) (1 2 3 1 4 1 2 6 8))
((0 0 0 0 0 0 0 0 1) (1 2 3 1 4 3 1 5))

NIL
&lt;/pre&gt;
&lt;p&gt;

That&#039;s more like it! So to toggle the bottom right square, we just
need to do the moves &quot;1 2 3 1 4 3 1 5&quot;? But the 3&#039;s and two of the 1&#039;a
cancel each other out so this is more complex than it needs to. As a
final fix we can modify my-xor so that instead of appending the move
identifiers, we collect the identifiers that are unique to each of the
moves we combine. The function we want to use for this is
set-exclusive-or:

&lt;/p&gt;
&lt;pre&gt;


FLIPPER 97 &gt; (set-exclusive-or (list 1 2 3) (list 2 3 4))
(4 1)

FLIPPER 98 &gt; (defun my-xor (a b)
               (list (xor (first a) (first b)) 
                     (set-exclusive-or (second a) (second b))))
MY-XOR

FLIPPER 103 &gt; (loop with foo = (copy-list *c-moves*)
                   for i from 0 to 8
                   do (let* ((bar (find-if #&#039;(lambda (x) (= 1 (nth i (first x)))) foo))
                             (gaz (remove bar foo)))
                        (setf foo 
                              (append (loop for move in gaz
                                            collect (if (= 0 (nth i (first move)))
                                                      move
                                                      (my-xor bar move)))
                                      (list bar)))
                        (format t &quot;~{~a~%~}~%&quot; foo)))
((0 0 1 1 1 0 0 0 0) (2 1))
((0 1 1 0 1 1 0 0 0) (3))
((0 1 0 0 1 0 1 0 0) (4 1))
((0 1 1 1 0 0 1 0 1) (5 1))
((0 0 1 0 0 1 0 0 1) (6))
((0 0 0 1 1 0 1 1 0) (7))
((0 0 0 0 0 0 1 1 1) (8))
((0 0 0 0 1 1 0 1 1) (9))
((1 1 0 1 1 0 0 0 0) (1))

((0 0 1 1 1 0 0 0 0) (2 1))
((0 0 1 0 0 1 1 0 0) (1 4 3))
((0 0 0 1 1 1 1 0 1) (1 5 3))
((0 0 1 0 0 1 0 0 1) (6))
((0 0 0 1 1 0 1 1 0) (7))
((0 0 0 0 0 0 1 1 1) (8))
((0 0 0 0 1 1 0 1 1) (9))
((1 0 1 1 0 1 0 0 0) (1 3))
((0 1 1 0 1 1 0 0 0) (3))

[snippety]

((1 0 0 0 0 0 0 0 0) (8 6 9 5))
((0 1 0 0 0 0 0 0 0) (7 2 9 4 6))
((0 0 1 0 0 0 0 0 0) (8 7 4 5))
((0 0 0 1 0 0 0 0 0) (2 9 4 3 8))
((0 0 0 0 1 0 0 0 0) (7 3 9 1 5))
((0 0 0 0 0 1 0 0 0) (2 7 1 6 8))
((0 0 0 0 0 0 1 0 0) (3 6 2 5))
((0 0 0 0 0 0 0 1 0) (8 3 4 6 1))
((0 0 0 0 0 0 0 0 1) (5 1 2 4))

NIL
&lt;/pre&gt;
&lt;p&gt;
Ok, we&#039;re done. We now know which moves we need to do to turn a single
square on or off. So we can now just toggle the ones we want. Let&#039;s just 
test it by toggling the top left corner (moves 8 6 9 5):
&lt;/p&gt;
&lt;pre&gt;

FLIPPER 105 &gt; (play-tty)
 0 0 1
 0 0 1
 1 0 0

8
 0 0 1
 0 0 1
 0 1 1

6
 0 0 0
 0 0 0
 0 1 0

9
 0 0 0
 0 1 1
 0 0 1

5
 1 0 1
 0 0 1
 1 0 0

&lt;/pre&gt;
&lt;p&gt; 
Excellent. &lt;br/&gt;

If you want to experiment further, you can try to combine what we now know and make a function that takes a starting position and returns which moves a player needs to do to solve a puzzle.
&lt;br/&gt;
Good luck!
&lt;/p&gt;
&lt;p&gt;
Feedback welcome at &lt;a href=&quot;mailto:asbjxrn@bjxrnstad.net&quot;&gt;asbjxrn@bjxrnstad.net&lt;/a&gt;
&lt;/p&gt;
</description>
    </item>
    <item>
      <title>The game</title>
      <link>http://www.jalat.com/blogs/lisp?id=1</link>
      <pubDate>Mon, 10 Jan 2006 09:33:57 GMT</pubDate>
      <description>&lt;h3&gt;Yet another newbie LISP example. &lt;/h3&gt;

&lt;p&gt;
When I was a little boy, my father got me a VIC-20, maybe in the hopes
of raising a famous computer scientist. But I never programmed a lot,
I just ended up playing a lot of games. So much for budding greatness.
&lt;/p&gt;
&lt;p&gt;
But one time my father brought me along to a computer fair. One stand
were showing off their machine by running a simple game on it. The 
game was simple enough that I figured I could make it myself. So when
I got home, I sat down and produced my only piece of software on the 
VIC-20. Ever since I&#039;ve had a soft spot for that simple puzzle.
&lt;/p&gt;
&lt;p&gt;
So what could be a more fitting subject for a beginners article than showing a lisp-implementation of: &lt;h3&gt; The Game!&lt;/h3&gt;
&lt;/p&gt;
&lt;p&gt;
The object of the game is to fill all the edge squares of a 3x3 grid, 
while the center square is unfilled. There are nine moves, each toggles
a number of squares on and off. Instead of trying to explain which moves
does what, I&#039;ll just lay out the initialization of the moves array and
let you figure it out yourself.
&lt;/p&gt;
&lt;pre&gt;
(defpackage :flipper
  (:use :common-lisp))

(in-package :flipper)

(defparameter *solution*
  &#039;(1 1 1
    1 0 1
    1 1 1))

(defparameter *moves*
  &#039;((1 1 0    ; 1  The array actually starts on 0, but these numbers 
     1 1 0    ;    make it easier to visualize
     0 0 0)

    (1 1 1    ; 2
     0 0 0
     0 0 0)
    
    (0 1 1    ; 3
     0 1 1
     0 0 0)
    
    (1 0 0    ; 4
     1 0 0
     1 0 0)
    
    (1 0 1    ; 5
     0 1 0
     1 0 1)
    
    (0 0 1    ; 6
     0 0 1
     0 0 1)
    
    (0 0 0    ; 7
     1 1 0
     1 1 0)
    
    (0 0 0    ; 8
     0 0 0
     1 1 1)
    
    (0 0 0    ; 9
     0 1 1
     0 1 1)))
&lt;/pre&gt;
&lt;p&gt;
Now, we need a function to generate a starting position for our
puzzle. By looking at the moves available, we can easily see that
any starting position is solvable, so let&#039;s just generate a random
list.
&lt;/p&gt;
&lt;pre&gt;
(defun create-puzzle ()
  (loop for i repeat 9
        collect (random 2)))
&lt;/pre&gt;
&lt;p&gt;
And let&#039;s see if it works:
&lt;/p&gt;
&lt;pre&gt;
CL-USER 1 &gt; (in-package :flipper)
#&amp;lt;PACKAGE FLIPPER&amp;gt;
 
FLIPPER 2 &gt; (create-puzzle)
(0 1 1 0 0 1 1 0 0)
&lt;/pre&gt;
&lt;p&gt;
Looks good. Now we need a function that applies moves to a position:
&lt;/p&gt;
&lt;pre&gt;
(defun apply-move (n position)
    (loop for p in position
          for m in (nth n *moves*)
          collect (mod (+ p m) 2)))
&lt;/pre&gt;
&lt;p&gt;
Does it work? (Remember that the move list is 0-indexed.):
&lt;/p&gt;
&lt;pre&gt;
FLIPPER 3 &gt; *solution*
(1 1 1 1 0 1 1 1 1)

FLIPPER 4 &gt; (apply-move 1 *solution*)
(0 0 0 1 0 1 1 1 1)

FLIPPER 5 &gt; (apply-move 0 *solution*)
(0 0 1 0 1 1 1 1 1)
&lt;/pre&gt;
&lt;p&gt;
Yup, still looks good.
&lt;br&gt;
Now, to actually play a game, all we need to do is
to go in a loop asking for moves and applying them until the current position
is equal to the solution:
&lt;/p&gt;
&lt;pre&gt;
(defun play-tty ()
  (do* ((startpos (create-puzzle))
        (move nil (- (read) 1))    ; Adjusting for the 0-indexed list
        (currentpos startpos (apply-move move currentpos))
        (moves 0 (incf moves)))
       ((equal currentpos *solution*) moves)
    (format t &quot;~a~%&quot; currentpos)))
&lt;/pre&gt;
&lt;p&gt;
And another test:
&lt;/p&gt;
&lt;pre&gt;
FLIPPER 6 &gt; (play-tty)
(0 0 1 1 0 1 0 1 1)
4
(1 0 1 0 0 1 1 1 1)
6
(1 0 0 0 0 0 1 1 0)
8
(1 0 0 0 0 0 0 0 1)
3
(1 1 1 0 1 1 0 0 1)
7
5
&lt;/pre&gt;
&lt;p&gt;
Well, it worked, but it&#039;s hard to visualize the moves, so lets make it
a bit more readable:
&lt;/p&gt;
&lt;pre&gt;
(defun print-grid (grid)
    (format t &quot;~{~{ ~a~}~%~}~%&quot; (loop for i on grid by &#039;cdddr
                                      collect (list (first i) (second i) (third i)))))

(defun play-tty ()
  (do* ((startpos (create-puzzle))
        (move nil (- (read) 1))
        (currentpos startpos (apply-move move currentpos))
        (moves 0 (incf moves)))
       ((equal currentpos *solution*) (progn
                                        (print-grid currentpos)
                                        (format nil &quot;Congratulations, you finished in ~a moves.&quot; moves)))
    (print-grid currentpos)))
&lt;/pre&gt;
&lt;p&gt;
And that is all the code you need for a working game:
&lt;/p&gt;
&lt;pre&gt;
FLIPPER 14 &gt; (play-tty)
 1 1 0
 0 1 1
 1 0 1

3
 1 0 1
 0 0 0
 1 0 1

2
 0 1 0
 0 0 0
 1 0 1

4
 1 1 0
 1 0 0
 0 0 1

6
 1 1 1
 1 0 1
 0 0 0

8
 1 1 1
 1 0 1
 1 1 1

&quot;Congratulations, you finished in 5 moves.&quot;
&lt;/pre&gt;
&lt;h3&gt;Adding flash!&lt;/h3&gt;
&lt;p&gt;
Now, it&#039;s a long time since people bothered to play text-games like
this. So let&#039;s add a GUI, people love that.
&lt;/p&gt;
&lt;p&gt;
I&#039;m going to use Lispworks CAPI library in this example. If you want
to follow along from here on, but don&#039;t have LispWorks installed on
your machine, you can download a free &quot;Personal Edition&quot; from
&lt;a href=&quot;http://www.lispworks.com/downloads/index.html&quot;&gt;LispWorks&lt;/a&gt;.
Even if you don&#039;t want to use CAPI you may want to read on, concepts
like callbacks and layouts are common to most graphical libraries, I think.
&lt;/p&gt;
&lt;p&gt;
First let&#039;s modify the package definition to gain access to the capi library:
&lt;/p&gt;
&lt;pre&gt;
(defpackage :flipper
  (:add-use-defaults t)
  (:use &quot;CAPI&quot;))
&lt;/pre&gt;
&lt;p&gt;
Our squares are just going to be simple output-panes, but we&#039;ll add a
slot in the class to keep track of which tile it is:
&lt;/p&gt;
&lt;pre&gt;
(defclass game-tile (output-pane)
  ((tilenum :accessor tilenum :initarg :tilenum)))
&lt;/pre&gt;
&lt;p&gt;
Now we can make a interface, let&#039;s put a &quot;New game&quot;, a &quot;Reset&quot; button
and a counter in a row above a grid with the tiles. We do that by
nesting a row-layout with the buttons and the counter inside a
column-layout.  We also need to specify callback functions for the
buttons and tiles. This is functions that will be called when the player 
clicks in our interface, we do not call the functions directly.
&lt;/p&gt;
&lt;pre&gt;
(define-interface game-window ()
  ((game-position :accessor game-position :initform *solution*)
   (start-position :accessor start-position :initform *solution*)   
   (num-moves :accessor num-moves :initform 0))
  (:panes
   (buttons push-button-panel :items &#039;(&quot;New puzzle&quot; &quot;Reset&quot;) :selection-callback &#039;button-callback )
   (counter display-pane :title &quot;Moves:&quot; :text &quot;0&quot; :title-position :left :accessor counter))
  (:layouts
   (header row-layout &#039;(buttons counter)
           :y-adjust :center)
   (tiles grid-layout
          (loop for i upto 8
                collect (make-instance &#039;game-tile
                                        :tilenum i
                                        :min-height 100
                                        :input-model &#039;(((:button-1 :press) make-move))))
          :rows 3
          :columns 3
          :accessor tiles)
   (game column-layout
         &#039;(header tiles)))
  (:default-initargs :title &quot;Flipper&quot;
   :layout &#039;game))
&lt;/pre&gt;
&lt;p&gt;
You can have a look at the interface by calling contain on an instance of the interface:
&lt;/p&gt;
&lt;pre&gt;
FLIPPER 17 &gt; (contain (make-instance &#039;game-window))
#&amp;lt;GAME-WINDOW &quot;Flipper&quot; 20715124&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
Hmm, the tiles are there, but we haven&#039;t drawn anything in them.
Instead of doing any actual drawing we&#039;ll just change the background
color according to the state of the tile. At the same time, I&#039;ll update the
move-counter. We can use the layout-description accessor to get a list
of the panes in the tiles grid:
&lt;/p&gt;
&lt;pre&gt;
(defun refresh-interface (interface)
  (loop for tile in (layout-description (tiles interface))
        for i upfrom 0
        do (setf (simple-pane-background tile) (if (= 1 (nth i (game-position interface)))
                                                 :red
                                                 :black)))
  (setf (display-pane-text (counter interface)) (format nil &quot;~a&quot; (num-moves interface))))
&lt;/pre&gt;
&lt;p&gt;
Let&#039;s try it out, if you didn&#039;t close the game-window you can just call
the function from the REPL:
&lt;/p&gt;
&lt;pre&gt;
FLIPPER 18 &gt; (refresh-interface *)
&quot;0&quot;
&lt;/pre&gt;
&lt;p&gt;
Now, if you have tried to click on any of the buttons or tiles, you
would have gotten an error because we haven&#039;t made the callback funtions 
we specified when defining the interface. Let&#039;s start with the buttons,
the callback functions for the buttons will be called with two arguments.
The first argument is the text written on the button, and the second argument
is the interface the button is located in. We will reuse the create-puzzle
function we defined earlier:
&lt;/p&gt;
&lt;pre&gt;
(defun new-puzzle (interface)
  (setf (start-position interface) (create-puzzle)
        (game-position interface) (start-position interface)
        (num-moves interface) 0)
  (refresh-interface interface))

(defun button-callback (data interface)
  (cond
   ((string= data &quot;New puzzle&quot;) (new-puzzle interface))
   (t (progn
        (setf (game-position interface) (start-position interface)
              (num-moves interface) 0)
        (refresh-interface interface)))))
&lt;/pre&gt;
&lt;p&gt;
Well, the &quot;New puzzle&quot; button works, but we can&#039;t test the reset
button since we&#039;re unable to make any moves. Let&#039;s add the
callback function for the tiles. Callback funtions for output-panes
are different from buttons. The first argument is the pane-object
itself, the second and third argument is the coordinates of the mouse
pointer when the pane was clicked. Useful when you want to draw something
where the mouse pointer clicks, but we&#039;ll ignore the coordinates.:
&lt;/p&gt;
&lt;pre&gt;
(defun make-move (self x y)
  (declare (ignore x y))
  (let ((interface (element-interface self)))
    (setf (game-position interface)
          (apply-move (tilenum self)
                      (game-position interface)))
    (incf (num-moves interface))
    (refresh-interface interface)))
&lt;/pre&gt;
&lt;p&gt;
Now, all that is left to do is to detect if the solution has been found.
We&#039;ll just add a test at the bottom of the make-move callback
function, and when the solution is found we&#039;ll show a popup
congratulating the player with a job well done and ask if the player
wants to play another game.
&lt;/p&gt;
&lt;pre&gt;
(defun make-move (self x y)
  (declare (ignore x y))
  (let ((interface (element-interface self)))
    (setf (game-position interface)
          (apply-move (tilenum self)
                      (game-position interface)))
    (incf (num-moves interface))
    (refresh-interface interface)
    (when (equal *solution* (game-position interface))
      (if (capi:popup-confirmer nil 
                                (format nil &quot;Congratulations, you finished the game in ~a moves. Do you want to play again?&quot;
                                        (num-moves interface))
                                :callback-type :none
                                :ok-button &quot;Sure, that was really fun&quot;
                                :no-button &quot;No way, I&#039;d rather watch paint dry&quot;
                                :cancel-button nil
                                :value-function #&#039;(lambda (dummy) t))
        (new-puzzle interface)
        (destroy interface)))))
&lt;/pre&gt;
&lt;p&gt;
Finally, let&#039;s throw in a convenience function to start the whole thing:
&lt;/p&gt;
&lt;pre&gt;
(defun play-gui ()
  (refresh-interface (display (make-instance &#039;game-window))))
&lt;/pre&gt;
&lt;p&gt;
Yes, folks, that&#039;s it. All you need to captivate a kid walking
past your stand at the local computer fair. 
&lt;br/&gt;
(&lt;a href=&quot;/static-files/flipper-linux.jpg&quot;&gt;Screenshot&lt;/a&gt; and &lt;a href=&quot;/static-files/flipper.lisp&quot;&gt;full source&lt;/a&gt;)
&lt;/p&gt;
&lt;p&gt;
Feedback welcome at &lt;a href=&quot;mailto:asbjxrn@bjxrnstad.net&quot;&gt;asbjxrn@bjxrnstad.net&lt;/a&gt;
&lt;/p&gt;
</description>
    </item>
  </channel>
</rss>
