<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>So Jake Says &#187; Lisp</title>
	<atom:link href="http://www.jakevoytko.com/blog/tag/lisp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jakevoytko.com/blog</link>
	<description>Ye Olde Computer Science Blogge</description>
	<lastBuildDate>Sun, 17 Jan 2010 15:16:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Everything You Need To Get Started With Common Lisp</title>
		<link>http://www.jakevoytko.com/blog/2008/12/29/everything-you-need-to-get-started-with-common-lisp/</link>
		<comments>http://www.jakevoytko.com/blog/2008/12/29/everything-you-need-to-get-started-with-common-lisp/#comments</comments>
		<pubDate>Mon, 29 Dec 2008 05:00:23 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[asdf-install]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[getting started with lisp]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[lisp implementation]]></category>
		<category><![CDATA[Paul Graham]]></category>
		<category><![CDATA[SBCL]]></category>
		<category><![CDATA[SLIME]]></category>
		<category><![CDATA[Superior Lisp Interaction Mode for Emacs]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/?p=343</guid>
		<description><![CDATA[Quick-Links for the TL;DR Crowd About Lisp: Describes Lisp as an overview. High Level Overview: Describes in general what is needed to program with Lisp. All you need SBCL Emacs SLIME asdf-install Code examples: A few rudimentary Lisp snippets. Other Lisp Features: Features that I did not feel like explaining Resources About Lisp Note: For [...]]]></description>
			<content:encoded><![CDATA[<blockquote>
<h2>Quick-Links for the TL;DR Crowd</h2>
<p><span style="text-decoration: underline;"><a href="#about">About Lisp</a>:</span> Describes Lisp as an overview.<br />
<span style="text-decoration: underline;"><a href="#high-level">High Level Overview</a>:</span> Describes in general what is needed to program with Lisp.<br />
<span style="text-decoration: underline;"><a href="#what-you-need">All you need</a></span></p>
<ul>
<li><span style="text-decoration: underline;"><a href="#sbcl">SBCL</a></span></li>
<li><span style="text-decoration: underline;"><a href="#emacs">Emacs</a></span></li>
<li><span style="text-decoration: underline;"><a href="#slime">SLIME</a></span></li>
<li><span style="text-decoration: underline;"><a href="#asdf-install">asdf-install</a></span></li>
</ul>
<p><span style="text-decoration: underline;"><a href="#starting">Code examples</a></span>: A few rudimentary Lisp snippets.<br />
<span style="text-decoration: underline;"><a href="#other-features">Other Lisp Features</a>:</span> Features that I did not feel like explaining <img src='http://www.jakevoytko.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<span style="text-decoration: underline;"><a href="#resources">Resources</a></span></p></blockquote>
<p><a name="about"></a></p>
<h2>About Lisp</h2>
<p><em><strong>Note:</strong> For a complete introduction, I recommend this <a href="http://www.gigamonkeys.com/book/">e-book</a>. If you only want to learn enough to get started, read on!</em></p>
<h3>Interactive</h3>
<p>Most languages take an input file and produce an executable or run a script. Lisp is interactive: all input is entered into the REPL, and the computation&#8217;s result is printed to the screen.</p>
<blockquote><p><strong>REPL:</strong> <strong>R</strong>ead <strong>E</strong>valuate <strong>P</strong>rint <strong>L</strong>oop. A C++ coder can think of it like this:</p>
<pre lang="c++">void lisp()
{
    while(true){
        cout&lt;&lt;"&gt;"; // prompt
        cout&lt;&lt;evaluate(read())&lt;&lt;endl;
    }
}</pre>
</blockquote>
<p>If you&#8217;ve ever used Python&#8217;s command line prompt, you&#8217;ve used a REPL. A bash prompt is a REPL. So is Lisp.</p>
<h3>Prefix</h3>
<p>Most expressions in C-style languages are prefix, but exceptions are made for arithmetic, such as 1/(x+3). All expressions in Lisp are prefix expressions: the first argument of an S-expression (Sexp) is a function name, and the rest of the atoms of the S-expression are the arguments for the function.  The following are examples of Lisp function calls:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>/ <span style="color: #cc66cc;">1</span> <span style="color: #66cc66;">&#40;</span>+ x <span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>         <span style="color: #808080; font-style: italic;">; 1/(x+3)</span>
<span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;~A~%&quot;</span> x<span style="color: #66cc66;">&#41;</span>    <span style="color: #808080; font-style: italic;">; prints the value of 'x' and a newline.</span></pre></div></div>

<h3>All Expressions Return Values</h3>
<p>All expressions in Lisp return values. For instance, the &#8216;<code>if</code>&#8216; statement in Lisp not only chooses which execution branch to follow, but returns the result of the executed expression. &#8216;<code>nil</code>&#8216; is the default return value of an expression, which also evaluates to false (&#8216;<code>t</code>&#8216; is true).</p>
<p>In C-style languages, expressions don&#8217;t necessarily return values. The expression &#8216;<code>1+3</code>&#8216; will return &#8216;<code>4</code>&#8216;, but <del datetime="2008-12-29T13:36:49+00:00">&#8216;<code>cout&lt;&lt;1+3</code>&#8216; doesn&#8217;t return anything</del><em> (They return a reference to an <code>ostream</code>, so this is a mistake</em>) void functions don&#8217;t return anything; they can&#8217;t be used as a sub-expression for a larger statement of code.</p>
<p>Functions in Common Lisp can return multiple values. The &#8216;<code>multiple-value-bind</code>&#8216; macro is used to bind multiple return values to multiple variables.<br />
<a name="high-level"></a></p>
<h2>High Level Overview: What You Need To Get Started</h2>
<p>1) <strong>An implementation</strong>. All you need is an implementation that conforms to the standards. All of them have an edge case or two, but odds are it won&#8217;t affect you. If you absolutely need to switch later (for CLisp&#8217;s fast arbitrary precision arithmetic, for instance), nothing is stopping you; most libraries support all popular implementations.</p>
<p>2) <strong>An editor</strong>. I personally recommend Emacs with the SLIME extension. You can also use <a href="http://www.vim.org/">Vim</a> and <a href="http://vim.sourceforge.net/scripts/script.php?script_id=2219">Limp</a> if you either prefer Vim or you can&#8217;t stand Emacs. I left Vim before I started using Emacs, so I&#8217;ve never used Limp. <em>Caveat emptor!</em></p>
<p>You don&#8217;t absolutely need to use an editor that interacts with Lisp. It&#8217;s POSSIBLE to run a Lisp program like a script, but it usually makes as much sense as opening a bag of chips with a hammer. You will want to use the REPL for most of your Lisp tasks, and this will only be bearable from within a good editor.</p>
<p>3) <strong>A Lisp tutorial or reference</strong>. I highly recommend &#8220;<span style="text-decoration: underline;"><a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FANSI-Common-Prentice-Artificial-Intelligence%2Fdp%2F0133708756%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1215999519%26sr%3D8-1&amp;tag=jakvoyshom-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">ANSI Common Lisp</a></span>&#8221; by Paul Graham [<a href="http://www.jakevoytko.com/blog/2008/07/14/review-of-ansi-common-lisp/">see my review</a>].</p>
<p>4) <strong>An installation system</strong>, like <a href="http://www.cliki.net/ASDF-Install">asdf-install</a>. Installation systems automatically load Lisp projects into your current image, and are essential for working with a large project. asdf-install allows you to download libraries from cliki.net and load them into your Lisp image from within the interactive Lisp command prompt!<br />
<a name="what-you-need"></a></p>
<h2>Details: What You Need To Get Started</h2>
<p><a name="sbcl"></a></p>
<h3>SBCL</h3>
<p><strong>About</strong></p>
<p>Steel Bank Common Lisp (SBCL) was forked from Carnagie-Mellon University Common Lisp (CMUCL) in 1999. It is named after Carnagie and Mellon&#8217;s respective industries, steel and banking.</p>
<p>Most Lisps can be interpreted or compiled, depending on the context. However, SBCL compiles all Lisp code it receives. Having used SBCL for 6 months or so, there&#8217;s not much of a pause even for large Lisp files. On the other hand, the compiler is very verbose, but this can be tweaked.</p>
<p><strong>Why SBCL: Popular</strong></p>
<p>Naturally, I can&#8217;t find good numbers on the popularity of SBCL. However, it is noteworthy that <a href="http://www.cliki.net/ASDF-Install">asdf-install</a> and LIMP were initially designed to work with <a href="http://www.vim.org/scripts/script.php?script_id=2219">SBCL</a>. This seems to be par for the course for all of the libraries I&#8217;ve used.</p>
<p><strong>Why SBCL: Active Development</strong></p>
<p>Development of SBCL is still roaring along, with 1,228 commits to their <a href="http://sourceforge.net/projects/sbcl/">Sourceforge</a> page at the time of writing, including several in the past few weeks. New releases come at the beginning of every month, and this month was no exception: version 1.0.23 was produced December 1, 2008.</p>
<h3>Installing SBCL</h3>
<p><strong>Installing SBCL: Linux</strong></p>
<p>SBCL can be installed like any other package:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">aptitude</span> <span style="color: #c20cb9; font-weight: bold;">install</span> sbcl
<span style="color: #666666; font-style: italic;"># Or your local variant.</span></pre></div></div>

<p>Once that&#8217;s finished, it&#8217;s easy to test the installation:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">jake<span style="color: #000000; font-weight: bold;">@</span>justalaptop:~<span style="color: #000000; font-weight: bold;">/</span>code<span style="color: #000000; font-weight: bold;">/</span>genesis$ sbcl
<span style="color: #7a0874; font-weight: bold;">&#40;</span>+ <span style="color: #000000;">2</span> <span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">*</span>
<span style="color: #000000;">4</span></pre></div></div>

<p><strong>Installing SBCL: Windows</strong></p>
<p>There is an &#8220;experimental&#8221; Windows installation binary: [<a href="http://prdownloads.sourceforge.net/sbcl/sbcl-1.0.22-x86-windows-binary.msi">link</a>].</p>
<p>I&#8217;ve ran it for brief periods and it seems to work fine, so I&#8217;m not sure what&#8217;s so experimental about it. Again, <em>Caveat emptor</em>!</p>
<p>After installation, run SBCL. You will get a command-line prompt, and type the following:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (+ 2 2)</span>
*
<span style="color: #cc66cc;">4</span></pre></div></div>

<p>It works!<br />
<a name="emacs"></a></p>
<h3>Emacs</h3>
<p>You can use whatever editor that you want to write Lisp. Emacs has good advantages:</p>
<p><strong>ELisp:</strong> Emacs is scripted in its own subset of Common Lisp. Called &#8216;elisp&#8217;, anybody who has been working with Lisp for a few months and can type &#8220;<a href="http://www.google.com/search?q=elisp+manual&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=com.ubuntu:en-US:unofficial&amp;client=firefox-a">ELisp manual</a>&#8221; into Google can customize Emacs to their taste.</p>
<blockquote><p><strong>Irony alert:</strong> I typed &#8220;elisp manula&#8221; into Google on my first try.</p></blockquote>
<p><strong>Automatic indentation:</strong> Yeah, I know, every editor in the history of the world does automatic indentation. However, Emacs&#8217; authors primarily write Lisp code, so they paid close attention to how Emacs interacts with Lisp. I rarely see Emacs do the Wrong Thing. When it does, I&#8217;m usually writing awful code.</p>
<p><strong>SLIME:</strong> The <strong>S</strong>uperior <strong>L</strong>isp <strong>I</strong>nteraction <strong>M</strong>ode for <strong>E</strong>macs. In order to effectively code in Lisp, you need an editor mode that will interact with a Lisp implementation. Typing the code directly into a command line is nice for small experiments, but is painful for anything more than 30 lines of code (for me at least.. your pain tolerance may vary).<br />
<a name="slime"></a></p>
<h3>SLIME</h3>
<p>SLIME combines the editing power of Emacs with the interactive nature of Lisp.</p>
<p>If you&#8217;ve ever used Python&#8217;s command-line prompt, you&#8217;re aware that it&#8217;s painful to use for any amount of time. The editing capability is limited to that of your console, and when you exit Python, all of your code disappears!</p>
<p>SBCL (and all other Lisp implementations) is no different. If this were the only option for working with Lisp, nobody would. You must work with the REPL from within a real editor. You COULD write code in an external file and load it into SBCL from the command line, but that removes the interactive nature of Lisp.</p>
<p>Enter SLIME (Superir Lisp Interactive Mode for Emacs). SLIME spawns a new Lisp process and acts as the liaison between you and the process.</p>
<p>To start the whole process, just type &#8220;<code>M-x slime</code>&#8220;, and a new REPL buffer opens. Any Lisp command can be entered into this buffer, and you get all of the editing commands from Emacs. <code>slime-mode</code> begins in all of your open Lisp buffers, which gives you code completion and function argument hints for all compiled functions.</p>
<p>If <code>slime-mode</code> is enabled in a Lisp buffer, you can compile the file with &#8220;<code>C-c C-k</code>&#8220;, or compile a single function with &#8220;<code>C-c C-c</code>&#8221; (it looks to me like dependencies are propagated correctly). SLIME knows what capability your Lisp has, so it can take advantage of implementation-specific capabilities like debugging.</p>
<p><strong>Installing SLIME</strong></p>
<p>SLIME is installed the same way as any other Emacs plugin:</p>
<ul>
<li>Download and extract.</li>
<li>Add the load path to your .emacs file</li>
<li>Add any other code snippets required.</li>
</ul>
<p>In this case, you&#8217;re going to be adding the following code to your .emacs file (open using &#8220;<code>M-x M-f ~/.emacs</code>&#8220;):</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>add-to-<span style="color: #b1b100;">list</span> 'load-path <span style="color: #ff0000;">&quot;&lt;em&gt;/the/path/to/slime&lt;/em&gt;&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span>require 'slime<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span>add-hook 'lisp-mode-hook <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>slime-mode t<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span>add-hook 'inferior-lisp-mode-hook <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>inferior-slime-mode t<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setq</span> inferior-lisp-program <span style="color: #ff0000;">&quot;sbcl&quot;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>I haven&#8217;t tested it on Windows, so I&#8217;m not sure if there are any extra gotchas. If you find that you&#8217;re running into undefined function errors, one possible workaround is to install Cygwin and add C:\cygwin\bin and c:\cygwin\usr\bin to your <code>%PATH%</code> environment variable. Some people run away in horror at the idea, so if you don&#8217;t like it, you&#8217;re on your own.<br />
<a name="asdf-install"></a></p>
<h3>asdf-install</h3>
<p>One thing that you should research is <a href="http://www.cliki.net/ASDF-Install">asdf-install</a>, a package manager for Lisp. If you find that you need a package that is found on cliki.net, you can download it with one step:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (require 'asdf-install) ; Not the one step.</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;ASDF-INSTALL&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (asdf-install:install 'postmodern) ; The one step.</span>
<span style="color: #b1b100;">NIL</span></pre></div></div>

<p>The above installs <a href="http://common-lisp.net/project/postmodern/">Postmodern</a>, a simple <a href="http://www.postgresql.org/">Postgres</a> interface for Common Lisp. Once you&#8217;ve done this, you only need to load the package into your Lisp image. This is also accomplished using <code>asdf-install</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (asdf:oos 'asdf:load-op :postmodern)</span>
<span style="color: #b1b100;">NIL</span></pre></div></div>

<p>Using those 3 lines, you can now start to define database connections and operations on the database, without ever leaving Emacs!<br />
<a name="starting"></a></p>
<h2>Starting to Code</h2>
<p>I highly recommend that you find a real reference or a real tutorial and start using that to write code. However, if you&#8217;re looking for things to enter into the REPL, I&#8217;ll give you some overviews of the basics of Lisp.</p>
<h3>Arithmetic</h3>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (+ 2 2)</span>
<span style="color: #cc66cc;">4</span></pre></div></div>

<p>This adds 2 and 2. Notice that Lisp arithmetic (and all Lisp functions) have prefix notation: the function name always comes first. You can nest values like the following:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (+ (+ 1 1) 1)</span>
<span style="color: #cc66cc;">3</span></pre></div></div>

<h3>Printing</h3>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (format t &quot;Hello, ~A~%&quot; &quot;Jacob&quot;)</span>
<span style="color: #ff0000;">&quot;Hello, Jacob&quot;</span>
<span style="color: #b1b100;">nil</span></pre></div></div>

<p>&#8216;<code>format</code>&#8216; is the function name. This is the Lisp-version of &#8216;<code>printf</code>&#8216;,</p>
<p>The second argument is the destination stream. You can give this &#8216;<code>t</code>&#8216; or &#8216;<code>nil</code>&#8216; for true or false, or the name of a stream.</p>
<p>When &#8216;<code>t</code>&#8216; is given, the value is printed to <code>Standard Output</code>. When &#8216;<code>nil</code>&#8216; is given, the value is returned as a string.</p>
<p>The third argument is the formatting string. &#8220;<code>~</code>&#8221; is the escape character. &#8220;<code>~A</code>&#8221; means that it takes an argument that follows (like <code>printf</code>), and <code>~%</code> is a newline.</p>
<p>There are other functions that you can use for printing, like &#8216;<code>princ</code>&#8216;. I usually stick with &#8216;<code>format</code>&#8216;, but there are different print semantics for different functions.</p>
<h3>Defining functions</h3>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (defun adding-function (arg1 arg2)</span>
    <span style="color: #ff0000;">&quot;Adds arg1 and arg2.&quot;</span>
    <span style="color: #66cc66;">&#40;</span>+ arg1 arg2<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
ADDING-<span style="color: #b1b100;">FUNCTION</span>
&nbsp;
<span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (adding-function 1 2)</span>
<span style="color: #cc66cc;">3</span>
&nbsp;
<span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (+ (adding-function 1 2) 1)</span>
<span style="color: #cc66cc;">4</span></pre></div></div>

<p>Here we see a function definition and two function calls. Let&#8217;s examine the function definition:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (defun adding-function (arg1 arg2)</span></pre></div></div>

<p>This can be considered the prototype line. &#8216;adding-function&#8217; is the name of the function. It takes two mandatory parameters, &#8216;arg1&#8242; and &#8216;arg2&#8242;, both with no default values.</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #ff0000;">&quot;Adds arg1 and arg2.&quot;</span></pre></div></div>

<p>This is the &#8220;documentation string.&#8221; A string may optionally be the first atom of a function, and it can be accessed from within Lisp using Lisp&#8217;s documentation reading abilities. Note that unlike wimpy strings in most languages, Lisp strings can contain newlines with no extra syntactical work.</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>+ arg1 arg2<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>This is the executed statement within the function body. A Lisp function returns the return value of the last statement. Since this is the only statement, it returns the addition of <code>arg1</code> and <code>arg2</code>.</p>
<h3>Defining variables</h3>
<p>Defining a variable for the first time in SBCL:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>defvar my-var<span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">; my-var is 'nil'.</span>
<span style="color: #66cc66;">&#40;</span>defvar my-var 'a-<span style="color: #b1b100;">value</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">; my-var is 'a-value'.</span></pre></div></div>

<p>Notice the quote in <code>'a-value</code>. The single quotation mark indicates that the following expression is <strong>data, not code</strong>. Otherwise, it would try to look up the value of the variable <code>a-value</code>, which we may or may not have defined. Either way, it&#8217;s not what we want.</p>
<p>If a variable is already defined, you can use &#8216;<code>setf</code>&#8216;:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (setf my-var 3)</span>
<span style="color: #cc66cc;">3</span></pre></div></div>

<h3>Conditionals</h3>
<p>For statements that only execute when something is true, use &#8216;<code>when</code>&#8216;. For statements that only execute when something is false, use &#8216;<code>unless</code>&#8216;.</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (when (= 1 1)</span>
    t<span style="color: #66cc66;">&#41;</span>
t
<span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (unless (= 1 1)</span>
    t<span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">nil</span></pre></div></div>

<p>For statements of the form &#8220;<code>if (true), do (x), otherwise do (y)</code>&#8220;, use &#8216;<code>if</code>&#8216;.</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (if expression</span>
    x
    y<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>If &#8216;<code>expression</code>&#8216; doesn&#8217;t evaluate to &#8216;<code>nil</code>&#8216;, then &#8216;<code>x</code>&#8216; is executed and its return value is returned. Otherwise, &#8216;<code>y</code>&#8216; is executed and its return value is returned.</p>
<p>For statements involving a lot of if, else-if clauses in other languages, use cond:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cond</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>test1<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>expression1<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>test2<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>expression2<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #808080; font-style: italic;">; ...</span>
      <span style="color: #66cc66;">&#40;</span>t <span style="color: #66cc66;">&#40;</span>default-expression<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<h3>Iteration</h3>
<p>The two easiest ways to iterate are the macros &#8216;<code>dotimes</code>&#8216; and &#8216;<code>dolist</code>&#8216;.</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (dotimes (i 3)</span>
    <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;~A&quot;</span> i<span style="color: #66cc66;">&#41;</span>
012
<span style="color: #b1b100;">nil</span></pre></div></div>

<p>&#8216;<code>dotimes</code>&#8216; is exactly as it sounds: it executes a statement a number of times. You assign a variable (in our case, &#8216;<code>i</code>&#8216;) and tell it the number of times it shall execute, and the variable takes on the values of all of the integers in the range <code>[0, n)</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (dolist (i '(1 2 3))</span>
    <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;~A&quot;</span> i<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #cc66cc;">123</span>
<span style="color: #b1b100;">nil</span></pre></div></div>

<p>&#8216;<code>dolist</code>&#8216; iterates through a list much in the same way &#8216;<code>dotimes</code>&#8216; does.</p>
<h3>Reduce</h3>
<p>The idea of &#8216;<code>reduce</code>&#8216; is to iterate through a set, applying a function to each value that acts as an accumulator. For instance, we can do this with addition:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (reduce #'+ '(1 2 3))</span>
<span style="color: #cc66cc;">6</span></pre></div></div>

<h3>Lambdas</h3>
<p>If you want to define your own functions for &#8216;<code>reduce</code>&#8216; without writing formal functions, you can do them as a &#8216;<code>lambda</code>&#8216;. That&#8217;s just a fancy word for &#8216;function with no name&#8217;. It consists of the name, the argument list, and a function body to execute:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (lambda (x) (+ x 2))</span></pre></div></div>

<p>This defines an anonymous function that adds 2 to the input given. The only difference from &#8216;<code>reduce</code>&#8216; is that we need to provide two parameters: the accumulated value and the next value in the list.</p>
<p>You&#8217;re going to use this. A lot. Formally defining every function is not worth it. A lot of Lisp code ends up much cleaner with functional approaches.</p>
<p>To define our own addition function for &#8216;<code>reduce</code>&#8216;:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; (reduce (lambda (x y) (+ x y)) '(1 2 3))</span>
<span style="color: #cc66cc;">6</span></pre></div></div>

<p><a name="other-features"></a></p>
<h2>Other features of Common Lisp</h2>
<ul>
<li>Macros: Creating code on-the-fly</li>
<li>CLOS: Common Lisp Object System. Lisp&#8217;s answer to Object Oriented programming.</li>
<li>Packages: This is how Lisp does namespacing.</li>
<li>More iteration constructs than you know what to do with.</li>
<li>&#8216;<code>mapcar</code>&#8216;: Apply a function to each element of a list</li>
<li>Hash tables</li>
<li>Arbitrary precision integers and numbers</li>
<li><code>cons</code>: &#8220;Construct&#8221; function. This is the function that builds lists.<code>car</code>: Returns the first element of a list.</li>
<li><code>cdr</code>: Returns the tail of a list (everything but the car).</li>
<li>Arbitrary binary manipulation</li>
<li>&#8216;<code>eval</code>&#8216;: Generate code from data at runtime.</li>
<li>File streams, input streams, output streams, stream redirections, oh my!</li>
<li>FFI: Foreign function interface. This lets you interface Lisp with C. You&#8217;ll probably need to do this if you want to add functionality to Common Lisp. It&#8217;s actually surprisingly easy to use.</li>
</ul>
<p><a name="resources"></a></p>
<h2>Resources</h2>
<p><strong>Books</strong></p>
<p><span style="text-decoration: underline;"><a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FANSI-Common-Prentice-Artificial-Intelligence%2Fdp%2F0133708756%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1215999519%26sr%3D8-1&amp;tag=jakvoyshom-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">ANSI Common Lisp</a></span> by Paul Graham. A great first Lisp book. It can be used as a textbook.</p>
<p><span style="text-decoration: underline;"><a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FParadigms-Artificial-Intelligence-Programming-Studies%2Fdp%2F1558601910%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1216001266%26sr%3D8-1&amp;tag=jakvoyshom-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">Paradigms of Artificial Intelligence Programming</a></span> by Peter Norvig. The best programming book I have ever read. It does have quite a bit on AI, but it also has extensive sections on advanced Lisp programming.</p>
<p><strong>Websites</strong></p>
<p><a href="http://www.sbcl.org/">SBCL:</a> The Lisp implementation I currently use.</p>
<p><a href="http://common-lisp.net/project/slime/">SLIME</a>: A Lisp interaction plugin for Emacs.</p>
<p><a href="http://vim.sourceforge.net/scripts/script.php?script_id=2219">Limp</a>: A SBCL plugin for Vim.</p>
<p><a href="http://cliki.net">cliki.net</a>: A general Lisp resource. The home of all projects remotely installable using asdf-install.</p>
<p><a href="http://cl-cookbook.sourceforge.net/">Common Lisp Cookbook</a>: An incomplete, yet still helpful, recipe book for Lisp code.</p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=343&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2008/12/29/everything-you-need-to-get-started-with-common-lisp/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Evolving Genetic Algorithms in Lisp</title>
		<link>http://www.jakevoytko.com/blog/2008/12/16/evolving-genetic-algorithms-in-lisp/</link>
		<comments>http://www.jakevoytko.com/blog/2008/12/16/evolving-genetic-algorithms-in-lisp/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 04:00:40 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[asdf-install]]></category>
		<category><![CDATA[Genesis]]></category>
		<category><![CDATA[Genetic Algorithms]]></category>
		<category><![CDATA[Genetic Programming]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[Mona Lisa]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/?p=329</guid>
		<description><![CDATA[Or, now with 100% more Genetic Algorithm! I&#8217;ve been programming a lot recently (instead of blogging about programming!). I caught the genetic algorithm bug along with the rest of the internet, so I&#8217;m in the middle of writing a Lisp library to make it easier to develop genetic algorithms: Genesis [Github link]. I&#8217;ve made some [...]]]></description>
			<content:encoded><![CDATA[<p><em>Or, now with 100% more Genetic Algorithm!</em></p>
<p>I&#8217;ve been programming a lot recently (instead of blogging about programming!). I caught the genetic algorithm bug along with the rest of the internet, so I&#8217;m in the middle of writing a Lisp library to make it easier to develop genetic algorithms: Genesis [<a href="http://github.com/jakevoytko/genesis/">Github link</a>].</p>
<p>I&#8217;ve made some progress in the past few weeks!</p>
<p>The first version of my program was only a genetic programming library, and barely. It produced a rule set that could be evaluated as a function, but it wasn&#8217;t anything different than hill-climbing (a phrase I learned from snobby Reddit commenters). It was inefficient, it was unwieldy, but it produced great results when it ran long enough.</p>
<p><strong>I&#8217;ve added a population!</strong> An arbitrary number of critters evolve in parallel at the moment. Previously, the individual would just mutate. I also added a basic gene-sharing algorithm: random merging.</p>
<p><strong>It&#8217;s faster!</strong> In my first version, I used two &#8216;<code>eval</code>&#8216;s per rule per round. Now I use 1, and I will cut it down to 2 per rule evaluation (instead of per round) soon.</p>
<p><strong>It&#8217;s in a package!</strong> I finally decided to <a href="http://www.jakevoytko.com/blog/2008/09/15/buddy-can-you-spare-a-namespace/">follow my own advice</a> and namespace everything properly. The package layout still needs work, as I&#8217;ve been too busy coding to figure out the ASDF system for installing packages.</p>
<p>The package system in Lisp is a lot more flexible than most module systems I&#8217;ve ever used, so I&#8217;ve been reading a few other popular Lisp packages to see how they are organized before I jump off the deep end without my swimmies.</p>
<p><strong>I started to add tests!</strong> Some of the functions are very fundamental in nature, so I&#8217;ve started to add solid tests for them.</p>
<p><strong>I segregated the example!</strong> There are currently 2 different files: genesis.lisp and square-root-sample.lisp. square-root-sample shows the code necessary to produce a simple/stupid example: finding an algorithm to calculate square roots. As I&#8217;ve mentioned before, the results are very good:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.jakevoytko.com/blog/wp-content/uploads/2008/12/sqrt-plot.gif" alt="Plot of f(x), abs(f(x)), error(x), and sqrt(x)" width="469" height="312" /></p>
<p>All you need to do in order to run this example is load genesis.lisp and square-root-sample.lisp and call the following:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>square-root-sample <span style="color: #66cc66;">&lt;</span>em<span style="color: #66cc66;">&gt;</span>generations population-size<span style="color: #66cc66;">&lt;</span>/em<span style="color: #66cc66;">&gt;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>After it has finished (run a small number of generations to get a sense for the time it takes), you can call the following to get the best answer so far:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>funcall-best *CURRENT-POPULATION* #'sample-fitness-<span style="color: #b1b100;">function</span> <span style="color: #cc66cc;">16</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<h2>Work Needed</h2>
<p>A recent popular example of genetic programming is the <a href="http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/">production of the Mona Lisa using random polygons.</a> My program should <em>almost</em> be able to handle this. I don&#8217;t allow for a &#8220;modify rule&#8221; function at the moment, only a &#8220;new rule&#8221; function. It would probably work, but convergence would be even slower than the example given.</p>
<p>I&#8217;m also not allowing for one of the most powerful methods of genetic algorithm development: binary serialization. Imagine: if you can represent your whole algorithm as a binary string, then crossover, reproduction, and mutation are all made trivial. I am instead using this idea for lists, which is convenient in Lisp, but I feel it lacks some of the punch.</p>
<h2>On The Horizon</h2>
<p>Of course, this is still in the toy phase. I still have a pretty substantial <a href="http://github.com/jakevoytko/genesis/tree/master/todo.org">to-do list</a>, but here are some of the high-notes:</p>
<ul>
<li>Finish writing tests for core functions.</li>
<li>Multiple populations, including cross-breeding between populations.</li>
<li>Add multithreading.</li>
<li>Give the user much greater control over (genetic-algorithm) by allowing extra key arguments.</li>
<li>Self-awareness: Gather statistics on which alterations produce better improvements, and make beneficial changes more likely to occur.</li>
</ul>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=329&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2008/12/16/evolving-genetic-algorithms-in-lisp/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Prototyping Genetic Algorithms in Lisp</title>
		<link>http://www.jakevoytko.com/blog/2008/12/04/prototyping-genetic-algorithms-in-lisp/</link>
		<comments>http://www.jakevoytko.com/blog/2008/12/04/prototyping-genetic-algorithms-in-lisp/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 12:00:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[asdf-install]]></category>
		<category><![CDATA[Genetic Algorithm]]></category>
		<category><![CDATA[genetic algorithm design]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[Sqrt]]></category>
		<category><![CDATA[Square root]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/?p=320</guid>
		<description><![CDATA[Source code for Genesis is here until I get asdf-install going. What are Genetic Algorithms? Genetic algorithms are one of the best things that computer science has produced. Rather than figuring out a good algorithm yourself, you let your random number generator find one while you sleep! Well, after an up-front design cost to generate [...]]]></description>
			<content:encoded><![CDATA[<p><em>Source code for Genesis is <a href="http://github.com/jakevoytko/genesis/tree/master">here</a> until I get asdf-install going.<br />
</em></p>
<h2>What are Genetic Algorithms?</h2>
<p>Genetic algorithms are one of the best things that computer science has produced. Rather than figuring out a good algorithm yourself, you let your random number generator find one while you sleep! Well, after an up-front design cost to generate proper random functions, and evaluating them, and determining how you&#8217;ll evolve them, and how long they should run&#8230;</p>
<p>I&#8217;ve long been interested in genetic algorithms, and now that I&#8217;ve learned my first language with an eval &#8212; Lisp &#8212; I&#8217;m starting to make a library. I spent the past few days prototyping and testing my code,<br />
and I got some encouraging initial results: I got a great almost-linear approximation to my simple test problem (finding square roots) using only addition, subtraction, multiplication, and division (see below).</p>
<p>I know, square roots. What a scorcher. But real people are making real solutions to real problems using genetic algorithms! NASA engineers produced an antenna. They determined acceptable design parameters for the antenna, figured out how to evaluate new designs, and let randomness determine the rest.</p>
<p>The result is described <a href="http://ti.arc.nasa.gov/projects/esg/research/antenna.htm">here</a>.</p>
<h2>My Genetic Algorithm Plans</h2>
<p>I want to produce a Lisp package over the next few weeks (since I should have a boatload of freetime around Christmas) that makes it easy to define new genetic algorithms. I&#8217;m going to do it in a few stages, and blog about intermediate results if and when they are interesting.</p>
<p>This will also give internet denizens plenty of opportunity to criticize my awful Lisp code! I am a nublet when it comes to Lisp, and I have no illusions about the quality of the code I&#8217;m writing.</p>
<p>This week: prototyping. I picked an easy problem to work out the basics of genetic algorithms. My problem? Finding square roots between 0 and 99, inclusive, with just one rule set.</p>
<blockquote><p><strong>Disclaimer</strong>: This is potentially the stupidest use of genetic programming known to man. Attempting to regularly solve numeric problems with genetic algorithms can lead to blindness, irrational exuberance towards Republican politics, and death.</p></blockquote>
<p>To give you a sense of the data it ingests, I present the main interface:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> genetic-algorithm <span style="color: #66cc66;">&#40;</span>generations starting-rules rule-fun
                          fitness-fun<span style="color: #66cc66;">&#41;</span>
  <span style="color: #ff0000;">&quot;Runs 'generations' number of generations. The rules are initially
  set to to 'starting-rules', the rule generating function is
  'rule-fun', and the evaluation function is 'fitness-fun'&quot;</span>
  <span style="color: #66cc66;">&#40;</span>prep-rules starting-rules<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">dotimes</span> <span style="color: #66cc66;">&#40;</span>gen-num generations<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>run-generation rule-fun fitness-fun<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Here is the invocation I used for my square root problem:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>genetic-algorithm <span style="color: #cc66cc;">32000</span> '<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>/ num <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>+ num <span style="color: #66cc66;">.</span>2<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
                   #'sample-rule-fun #'sample-fitness-fun<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The typical work for defining genetic algorithms is split into a few stages:</p>
<p>1) Problem definition: What do I even want to solve?<br />
2) Evaluation function: How far am I from right?<br />
3) Picking components: How can I build my algorithms randomly?</p>
<p><strong>Problem Definition</strong></p>
<p>Find the square root of an integer, n, in the range [0, 99].</p>
<p><strong>Evaluation Function</strong></p>
<p>Sum of the squared error of all of the integers in the problem statement.</p>
<p>Interestingly, we can predict the quality and form of the results: since we are minimizing the sum of the squared errors, the result should mimic a least-squared approach. Since I&#8217;m only using basic arithmetic, it probably won&#8217;t be a very good one (linear at best..).</p>
<h2>Prototype Implementation</h2>
<p><em>Warning: There be dragons in the parens ahead.</em></p>
<p>The rules are stored as a list of lists:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>defvar *RULES* <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>We also store the possible operators:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>defvar *sample-nodes* #<span style="color: #66cc66;">&#40;</span>leaf<span style="color: #66cc66;"> + </span>leaf<span style="color: #66cc66;"> - </span>leaf<span style="color: #66cc66;"> / </span>leaf<span style="color: #66cc66;"> * </span>leaf<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Woah, what&#8217;s with all of the &#8220;leaf&#8221;s? Well, a balanced binary tree has about as many nodes as leafs (I&#8217;m generalizing&#8230;), so I started at leaf/operator parity and moved up until I stopped getting stack overflows when generating new functions, which happened at one <img src='http://www.jakevoytko.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>How do the leafs get translated into values? First, they are picked from an array of random values:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>defvar *sample-values*
    #<span style="color: #66cc66;">&#40;</span>-<span style="color: #cc66cc;">1</span> <span style="color: #cc66cc;">1</span> num num randomnum randomfrac<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> sample-generate-leaf <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #ff0000;">&quot;Picks a random element from 'list' and translates it into the proper atom
  or list.&quot;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>elt <span style="color: #66cc66;">&#40;</span>random-array-element <span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">case</span> elt
         <span style="color: #66cc66;">&#40;</span>randomnum <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">random</span> <span style="color: #cc66cc;">1024</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#40;</span>randomfrac
          <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>val <span style="color: #66cc66;">&#40;</span>ignore-errors <span style="color: #66cc66;">&#40;</span>/ <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">random</span> <span style="color: #cc66cc;">1024</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">random</span> <span style="color: #cc66cc;">1024</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
            <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">when</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null</span> val<span style="color: #66cc66;">&#41;</span>
              <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setf</span> val <span style="color: #66cc66;">&#40;</span>/ <span style="color: #cc66cc;">1</span> <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
            val<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#40;</span>t elt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>These are pretty self descriptive (<em>num</em> is the input number, and it is included twice because I got better results <img src='http://www.jakevoytko.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ). &#8216;<em>randomnum</em>&#8216; is a random integer in [0, 1023], and &#8216;<em>randomfrac</em>&#8216; is a fraction whose<br />
coefficients are in [0, 1023].</p>
<p>So how is all of this put together?</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> sample-rule-fun <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #ff0000;">&quot;Example random rule generator. Generates a random arithmetical
  expression.&quot;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>elt <span style="color: #66cc66;">&#40;</span>random-array-element *sample-nodes*<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">case</span> elt
      <span style="color: #66cc66;">&#40;</span>leaf <span style="color: #66cc66;">&#40;</span>sample-generate-leaf *sample-values*<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#40;</span>t
       <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">append</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">list</span> elt<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>at-least-once #'sample-rule-fun<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> sample-generate-leaf <span style="color: #66cc66;">&#40;</span>arr<span style="color: #66cc66;">&#41;</span>
  <span style="color: #ff0000;">&quot;Picks a random element from 'arr' and translates it into the proper atom
  or list.&quot;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>elt <span style="color: #66cc66;">&#40;</span>random-array-element arr<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">case</span> elt
    <span style="color: #66cc66;">&#40;</span>randomnum <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">random</span> <span style="color: #cc66cc;">1024</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>randomfrac
     <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>val <span style="color: #66cc66;">&#40;</span>ignore-errors <span style="color: #66cc66;">&#40;</span>/ <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">random</span> <span style="color: #cc66cc;">1024</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">random</span> <span style="color: #cc66cc;">1024</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
       <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">when</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null</span> val<span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setf</span> val <span style="color: #66cc66;">&#40;</span>/ <span style="color: #cc66cc;">1</span> <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">;; avoid divide by zero</span>
       val<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>t elt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>This is also fairly straightforward: if you pick an operator, generate a new list, if you pick a leaf, generate a new value.</p>
<h2>Results</h2>
<h3>Square Root Function Test</h3>
<p>I ran it for about 18 hours (overnight and after work), and when I came back, the results were nothing short of amazing:</p>
<p><a href="http://www.jakevoytko.com/blog/wp-content/uploads/2008/12/sqrt-plot.gif"><img class="alignnone size-full wp-image-322" title="sqrt-plot" src="http://www.jakevoytko.com/blog/wp-content/uploads/2008/12/sqrt-plot.gif" alt="" width="500" height="332" /></a></p>
<p>I included a range of values outside of the initial zone because the results are better than I could have hoped for.</p>
<p>I saved the data, and then was trying to save the rules (there were 18 in all), and then I lost them from my first Emacs freeze. C&#8217;est la vie. However, my initial guess that the data would fit as a least-squares appears to be a better guess than I ever could have hoped. I want to add arbitrary polynomials, and I hope to see a higher-order best-squares fit of the data plot, with much less error.</p>
<h3>Implementation Time</h3>
<p>The first implementation was done in a 4-hour chunk of one evening (during which I played X-Moto for at least an hour&#8230;), which I find impressive. I probably would have spent at least 3 times that on the prototype in C++. This problem is made extremely because of several of Lisp&#8217;s features:</p>
<p><strong>eval</strong>: My method is based on runtime list generation, and eval-ing it as a lambda.</p>
<p><strong>Insanely simple Lisp syntax</strong>: The same syntax that defines lists also defines their programs? This reduces random function generation to a random list generation problem, which is almost trivial.</p>
<p><strong>REPL:</strong> Lisp is a REPL (<strong>r</strong>ead-<strong>e</strong>val-<strong>p</strong>rint <strong>l</strong>oop) language, meaning that it has an interactive prompt. Combining this with Emacs&#8217; multiple buffer capabilities, and it&#8217;s super easy to make changes and reload.</p>
<h2>TODO</h2>
<p>It&#8217;s never finished!</p>
<h3>Rules</h3>
<p>Allow more than one rule set, define the maximum number of rules per set, define rules as arrays for better lookup, etc.</p>
<h3>Better use of eval</h3>
<p>I eval the rules every time I need them, as opposed to the once I should generate them. I will probably see a significant speedup when I do this.</p>
<h3>Define a package</h3>
<p>Namespacing everything has obvious benefits.</p>
<h3>Cross-breed rules</h3>
<p>Allow true genetic properties by copying subsets of rules into other rules.</p>
<h3>Better rule trimming</h3>
<p>My current program produces some stupid rules: such as f(x)=x. In fact, my &#8220;amazing results&#8221; had 4 rules that evaluated a number to itself out of a total if 18 rules.</p>
<h3>Allowing the user to define rule inputs.</h3>
<h3>Putting the package in an easy-to-use location</h3>
<p>Stay tuned for more!</p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=320&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2008/12/04/prototyping-genetic-algorithms-in-lisp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Lisp is Changing My C++</title>
		<link>http://www.jakevoytko.com/blog/2008/10/06/lisp-is-changing-my-c/</link>
		<comments>http://www.jakevoytko.com/blog/2008/10/06/lisp-is-changing-my-c/#comments</comments>
		<pubDate>Mon, 06 Oct 2008 04:00:59 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Generalization]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[Paul Graham]]></category>
		<category><![CDATA[Peter Norvig]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/?p=167</guid>
		<description><![CDATA[I am a mild-mannered C#/C++ programmer by day, and I have been learning Lisp in my spare time. Comparatively speaking, I do not spend much time programming for personal projects (only an hour or two a day), but I noticed something awesome recently: Lisp is influencing the way I write C++ in a few different [...]]]></description>
			<content:encoded><![CDATA[<p>I am a mild-mannered C#/C++ programmer by day, and I have been learning Lisp in my spare time. Comparatively speaking, I do not spend much time programming for personal projects (only an hour or two a day), but I noticed something awesome recently:</p>
<p>Lisp is influencing the way I write C++ in a few different ways.</p>
<h2>To Generalize&#8230;</h2>
<p>Imagine my horror: Lisp caused me to realize that I&#8217;ve been refactoring the <em>wrong way</em>! For a few years!</p>
<p>Well, that is not <em>entirely</em> accurate. My code did the same thing after I was done. I broke code down into small logical units. Unless I was careless, the code still worked. My functions were more readable, and one could usually see what they did at a glance.</p>
<p>I asked myself questions along the lines of, &#8220;What can I do to break this up logically?&#8221;, and therein lies the problem:</p>
<blockquote><p><strong>Weak questions have weak answers.</strong></p></blockquote>
<p>Powerful questions are much better suited to refactoring!</p>
<ul>
<li>&#8220;Can I use an existing solution to solve this?&#8221;</li>
<li>&#8220;Could this solve a completely unrelated problem?&#8221;</li>
<li>&#8220;Can I rearrange things elsewhere so that this code isn&#8217;t even needed?&#8221;</li>
</ul>
<p>Sometimes, the answer is no. Some boilerplate code (like exception catching) is an overhead that can not be avoided, can not usually be generalized, and sticks out like a sore thumb in C++ style languages.</p>
<p>Why did Lisp fundamentally shape my refactoring practices? Paul Graham and Peter Norvig are both to blame for this, and for different reasons.</p>
<p>First up, Graham. I taught myself from &#8220;<a href="http://www.jakevoytko.com/blog/2008/07/14/review-of-ansi-common-lisp/">ANSI Common Lisp</a>&#8220;. At first, I attacked the problems in the book from a C++ perspective, trying to wedge loops and functions into my solutions. Doing the Lisp examples forced me to think simpler. Within a month I started being able to think of functional solutions instead of C++ solutions (reaching for reduce and lambdas instead of loops and classes).</p>
<p>I worked problems out of this book every night for a month and a half, and it still sits next to me as a quick reference. After 8 years of C++ programming, it took a while for things like &#8220;reduce&#8221; to become the most obvious solution to a problem.</p>
<p>I haven&#8217;t reached that magical enlightening moment that Lisp causes. I don&#8217;t have the &#8220;ooh, shiny!&#8221; awe over macros that seasoned Lisp programmers seem to have, so I&#8217;m still hacking away.</p>
<p>Norvig has sent me towards enlightenment with <a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FParadigms-Artificial-Intelligence-Programming-Studies%2Fdp%2F1558601910&amp;tag=jakvoyshom-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=jakvoyshom-20&amp;l=ur2&amp;o=1" border="0" alt="" width="1" height="1" />. In these pages, I found something that was missing from Graham: elegance</p>
<p>Some of the solutions that I see in this book give me a sense of awe and enlightenment that I haven&#8217;t had since I took Abstract Algebra. He presents them in a very straightforward and honest style that can only come with experience.</p>
<p>This book has given me a whole new level of quality to try to reach. I hope one day to be able to do this.</p>
<h2>Tools</h2>
<p>A year ago, I would have described my programming process like this:</p>
<ol>
<li>Design</li>
<li>Code + document</li>
<li>Neaten + prune</li>
<li><em>Return to 1, as needed</em></li>
</ol>
<p>Not bad. However, working with Lisp and seeing that there are different tools in the world has led me to fundamentally restructure how I program. I would now describe my process like this:</p>
<ol>
<li>Design</li>
<li>Code + document</li>
<li>&#8220;Would a tool/function/class have made this task easier?&#8221;</li>
<li><em>Return to 1, as needed</em>.</li>
</ol>
<p>For instance, I&#8217;m writing some image processing libraries in CL right now, and I&#8217;ve written a few tools that I might never have thought of generalizing from a pure-C++ mindset! After all, iterating over an image is really easy in C++, so why bother making it simpler?</p>
<p>However, <code>map-image</code> is invaluable: apply a function at each pixel of an image, and return a new image. Combine this with the <code>lambda</code> construct, and you have a level of flexibility possible only with some of the goofier Boost libraries.</p>
<h2>In Short&#8230;</h2>
<p>While working through the Graham examples, I found that I was playing Code Golf against myself.</p>
<p>I&#8217;ve started to see this carry over to my coding at work as well. In the past, I might have done something like the following:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> num_times <span style="color: #000080;">=</span> SomeFunction<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">return</span> AnotherFunction<span style="color: #008000;">&#40;</span>num_times<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>This is a reasonable approach. The local variable name reflects the role of the function, and adds a little bit of clarity for the human reader. Using this style is fine if these are your priorities.</p>
<p>However, I&#8217;ve started giving functions better names (when I can), and cutting out the middleman:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">return</span> AnotherFunction<span style="color: #008000;">&#40;</span>NumberOfTimes<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>This is effectively the same code, and there&#8217;s a good chance that it would compile down to the same assembly language. It&#8217;s just as readable. The difference is the line count. It&#8217;s a difference small enough for a <a href="http://www.bikeshed.com/">bikeshed issue holy war</a>, but over the course of small projects (all I&#8217;ve done so far in Lisp), being able to fit more code on my screen is a big win for me (all else equal).</p>
<p>I am starting to prefer reading and writing compressed code as a result of trying to solve Graham&#8217;s examples in as few lines as possible.</p>
<h2>Future Directions</h2>
<p>I&#8217;m still looking for my &#8220;Lisp Enlightenment&#8221; with respect to macros, which leads me to believe that there&#8217;s something significant that I&#8217;m still not getting about Common Lisp. I&#8217;m not sure where all of these new techniques are going to lead me, but in the meantime, it is starting to fundamentally change how I approach programming problems.</p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=167&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2008/10/06/lisp-is-changing-my-c/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Learning Lisp Through Examples: XHTML Generation</title>
		<link>http://www.jakevoytko.com/blog/2008/08/11/learning-lisp-through-examples-xhtml-generation/</link>
		<comments>http://www.jakevoytko.com/blog/2008/08/11/learning-lisp-through-examples-xhtml-generation/#comments</comments>
		<pubDate>Mon, 11 Aug 2008 04:00:09 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[defpackage]]></category>
		<category><![CDATA[Learning Lisp]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[XHTML]]></category>
		<category><![CDATA[XHTML generation]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/?p=123</guid>
		<description><![CDATA[I&#8217;ve learned a subset of Common Lisp that is large enough to start writing programs. This uncovered a small problem: how do I know I&#8217;m doing it right? Lisp is an old language, and there are ancient conventions and standards written deep in the caverns of MIT. Fortunately for me, the internet is best used [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve learned a subset of Common Lisp that is large enough to start writing programs. This uncovered a small problem: how do I know I&#8217;m doing it right? Lisp is an old language, and there are ancient conventions and standards written deep in the caverns of MIT.</p>
<p>Fortunately for me, the internet is best used to tell people they are wrong. <strong>I&#8217;ll show you my code, and you tell me when I&#8217;m doing it wrong. Deal? </strong></p>
<p>For the complete source code listing, <a href="http://jakevoytko.com/src/xhtml.lisp">click here</a>. I don&#8217;t have any public version control set up to date, so it&#8217;s just a static file.</p>
<p>If you are a Lisp power user, this will be horribly boring. I&#8217;m just looking to see where I make mistakes.</p>
<blockquote><p><strong>Disclosure</strong>: I did not write unit tests for this project, and I&#8217;m aware that this constitutes &#8220;doing it wrong.&#8221; I recently discovered &#8220;<a href="http://www.cs.northwestern.edu/academics/courses/325/readings/lisp-unit.html">lisp-unit</a>&#8220;, and will be rectifying the situation.</p>
<p>I also make no effort to validate or encode user input strings.</p></blockquote>
<h2>XHTML Syntax</h2>
<p>The &#8220;XHTML&#8221; referred to will be considered Transitional XHTML, since tags like &lt;<code>center</code>&gt; are not explicitly disallowed.</p>
<p>Basically, I wanted the program to convert something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;">'<span style="color: #66cc66;">&#40;</span>html
 <span style="color: #66cc66;">&#40;</span>head
  <span style="color: #66cc66;">&#40;</span>title <span style="color: #ff0000;">&quot;Greetings, Terran orb!&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
 <span style="color: #66cc66;">&#40;</span>body
  <span style="color: #66cc66;">&#40;</span>img <span style="color: #ff0000;">&quot;src&quot;</span> <span style="color: #ff0000;">&quot;./img/some_image.jp2&quot;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span>p <span style="color: #66cc66;">&#40;</span>** <span style="color: #ff0000;">&quot;margin&quot;</span> <span style="color: #ff0000;">&quot;1em&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #ff0000;">&quot;Some paragraph&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>into this:</p>
<pre>&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;
   "Greetings, Terran orb!"
  &lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
  &lt;img src="./img/some_image.jp2"/&gt;
  &lt;p margin="1em"&gt;
   Some paragraph
  &lt;/p&gt;
 &lt;/body&gt;
&lt;/html&gt;</pre>
<p>There will be a separate function to generate the DOCTYPE declaration.</p>
<p>The biggest eyesore here is the (**) tags used for attributes. However, I don&#8217;t use very many attributes in my coding, so it&#8217;s easier for me to specify when I have an attribute than to use the following syntax:</p>
<pre><em>(tag attributes inner-stuff)
</em></pre>
<p>and have my code scattered with more <code>nil</code> than you can shake a stick at.</p>
<h2>A Summary of my Development</h2>
<p>Based on memory and SVN commit messages.</p>
<p>1. I&#8217;m going to print some tags!</p>
<p>2. OK, I screwed up the first time, but I&#8217;m really going to print some tags this time!</p>
<p>3. Attributes are now supported.</p>
<p>4. Singleton elements are now supported.</p>
<p>5. Holy hell, &#8220;FORMAT&#8221; is complicated! All I want to do is indent! I am also adding code to specify the output stream.</p>
<p>6. I have realized that it is simpler to redirect <code>*standard-output*</code> than it is to specify the stream.</p>
<p>7. DOCTYPEs are supported.</p>
<p>8. It turns out that XHTML tags are mandated to be lowercase. Who knew?!</p>
<h2>Walking Through My Code</h2>
<p><strong>Package definitions</strong></p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>defpackage <span style="color: #ff0000;">&quot;XHTML&quot;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">use</span> <span style="color: #ff0000;">&quot;COMMON-LISP&quot;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">export</span> <span style="color: #ff0000;">&quot;GENERATE&quot;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">export</span> <span style="color: #ff0000;">&quot;DOCTYPE&quot;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">export</span> *singletons*<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>in-package XHTML<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>defparameter *singletons* '<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;IMG&quot;</span> <span style="color: #ff0000;">&quot;META&quot;</span> <span style="color: #ff0000;">&quot;LINK&quot;</span> <span style="color: #ff0000;">&quot;HR&quot;</span> <span style="color: #ff0000;">&quot;BR&quot;</span> <span style="color: #ff0000;">&quot;INPUT&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The only interesting thing here are the exports. &#8220;<code>GENERATE</code>&#8221; is the function that will be generating the XHTML. &#8220;<code>DOCTYPE</code>&#8221; allows you to generate the DOCTYPE with an optional argument to specify the location of the DTD.</p>
<p><code>*singletons*</code> is a list of singleton elements (Elements like &lt;<code>img</code> /&gt; or &lt;<code>meta</code> /&gt;), and is available to the user as a helper. It will be more useful if/when I alter this to be an XML generator.</p>
<p><strong>Function: <code>GENERATE</code></strong></p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> generate <span style="color: #66cc66;">&#40;</span>lst <span style="color: #66cc66;">&amp;</span>amp<span style="color: #808080; font-style: italic;">;optional (depth 0))</span>
  <span style="color: #ff0000;">&quot;Recursively outputs a list of pseudo-xhtml as real xhtml to *standard-output*. Does not print doctype.&quot;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cond</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null</span> lst<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>stringp lst<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;~VT~A&quot;</span> depth lst<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">atom</span> lst<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;~A &quot;</span> lst<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>singleton? lst<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>print-singleton lst <span style="color: #66cc66;">&#40;</span>+ depth <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">listp</span> lst<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>print-tag <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> lst<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> lst<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>+ depth <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Calling <code>(xhtml-generate my-list)</code> will print the desired output to <code>*standard-output*</code>. The program recursively partitions the work, but all tag calls inevitably go through this function. Atoms are included so that the user is not punished if they slip and forget to quote their sentences (unless they consider caps-lock a punishment).</p>
<p><code>(p This is a paragraph!)</code></p>
<p>Will be output as</p>
<p><code>&lt;p&gt;THIS IS A PARAGRAPH!&lt;/p&gt;</code>.</p>
<p>They will still get an admonishment (from SBCL, anyways) if there are commas in the text, but this is a happy medium for compromise.</p>
<p><strong>Function: <code>DOCTYPE</code></strong></p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> doctype <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&amp;</span>amp<span style="color: #808080; font-style: italic;">;optional (dtd-loc &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;))</span>
  <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;&quot;</span> dtd-loc<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>This is included separately so the user can use a different DOCTYPE declaration.</p>
<p><strong>Function: <code>PRINT-TAG</code></strong></p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> print-tag <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">name</span> lst <span style="color: #66cc66;">&amp;</span>amp<span style="color: #808080; font-style: italic;">;optional (depth 0))</span>
  <span style="color: #ff0000;">&quot;Prints a normal html tag. Parameters are the name of the element and a list of elements that are children of this tag. If the first element of the parameter `lst` is a list whose first element is the atom **, then this list is treated as an attribute list.&quot;</span>
  <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;~&amp;amp;~VT&amp;lt;~(~A~)&quot;</span> depth <span style="color: #b1b100;">name</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>cur-lst lst<span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>head <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> lst<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cond</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null</span> lst<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span>
          <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">and</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">listp</span> head<span style="color: #66cc66;">&#41;</span>
                <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">equal</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> head<span style="color: #66cc66;">&#41;</span> '**<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
           <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">progn</span>
             <span style="color: #66cc66;">&#40;</span>print-atts <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> head<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
             <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setf</span> cur-lst <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> lst<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;&amp;gt;~&amp;amp;&quot;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">mapcar</span> #'<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span><span style="color: #66cc66;">&#40;</span>x<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>generate x <span style="color: #66cc66;">&#40;</span>+ depth <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> cur-lst<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;~&amp;amp;~VT&lt;!--~(~A~)--&gt;~&amp;amp;&quot;</span> depth <span style="color: #b1b100;">name</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Most of my time writing and rewriting this function was spent in the &#8220;<code>FORMAT</code>&#8221; docs, as it is far more complicated than <a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FANSI-Common-Prentice-Artificial-Intelligence%2Fdp%2F0133708756%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1214268519%26sr%3D8-1&amp;tag=jakvoyshom-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">ANSI Common Lisp</a> ever suggested. Not only can it do any type of formatting under the sun, but it can also butter your toast and summon dead relatives.</p>
<p>The logic of this function is almost identical to the simpler &#8220;<code>PRINT-SINGLETON</code>&#8221; below. The added ugly checks to see if we have attributes to print. The first line and the last 3 lines are all that is really important with respect to the logic of the function.</p>
<p><strong>Function: <code>SINGLETON?</code></strong></p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> singleton? <span style="color: #66cc66;">&#40;</span>inpt<span style="color: #66cc66;">&#41;</span>
  <span style="color: #ff0000;">&quot;Checks to see if 'inpt' is a singleton (e.g. &lt;img alt=&quot;</span><span style="color: #ff0000;">&quot; /&gt;)&quot;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cond</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null</span> inpt<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">not</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">listp</span> inpt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>t <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">member</span> <span style="color: #66cc66;">&#40;</span>symbol-<span style="color: #b1b100;">name</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> inpt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
                   *singletons*
                   <span style="color: #66cc66;">:</span><span style="color: #555;">test</span> #'<span style="color: #b1b100;">equal</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p><strong>Function: <code>PRINT-SINGLETON</code></strong></p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> print-singleton <span style="color: #66cc66;">&#40;</span>lst <span style="color: #66cc66;">&amp;</span>amp<span style="color: #808080; font-style: italic;">;optional (depth 0))</span>
  <span style="color: #ff0000;">&quot;Handles singleton (&lt;img alt=&quot;</span><span style="color: #ff0000;">&quot; /&gt;, etc.) statements. Parameter: A list whose car
is the singleton in question, and any remaining elements are considered
attributes. Optional: The indentation depth.&quot;</span>
  <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;~&amp;amp;~VT&amp;lt;~(~A~)&quot;</span> depth <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> lst<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span>print-atts <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> lst<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;/&amp;gt;~&amp;amp;&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>This is the simpler version of &#8220;<code>PRINT-TAG</code>&#8221; written above. This function is a lot simpler because any extra elements in the list are assumed to be attributes. We don&#8217;t have the possibility of attributes that are mixed with tags.</p>
<p><strong>Function: <code>PRINT-ATTS</code></strong></p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> print-atts <span style="color: #66cc66;">&#40;</span>lst<span style="color: #66cc66;">&#41;</span>
  <span style="color: #ff0000;">&quot;Prints attribute lists. There must be an even number of parameters,
the odd parameters being the names and the even parameters being attributes.&quot;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null</span> lst<span style="color: #66cc66;">&#41;</span>
      <span style="color: #b1b100;">nil</span>
      <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">progn</span>
        <span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot; ~A=<span style="color: #000099; font-weight: bold;">\&quot;</span>~A<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> lst<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">nth</span> <span style="color: #cc66cc;">1</span> lst<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>print-atts <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> lst<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Pretty boring, as things go.</p>
<h2>Future Directions</h2>
<p><strong>Generating Related Pages</strong></p>
<p>I would like to generate pages that are related. They use the same CSS, refer to the same image directories, and perhaps have the same navigation elements.</p>
<p><strong>Database connections</strong></p>
<p>Does anybody have any suggestions for good database interfaces [such as <a href="http://clsql.b9.com/documentation.html">CLSQL</a>]?</p>
<p><strong>Running as CGI under Apache</strong></p>
<p>The last thing that I will need in order to make simple client-server web applications.</p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=123&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2008/08/11/learning-lisp-through-examples-xhtml-generation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Explaining Lisp to my Father</title>
		<link>http://www.jakevoytko.com/blog/2008/07/21/explaining-lisp-to-my-father/</link>
		<comments>http://www.jakevoytko.com/blog/2008/07/21/explaining-lisp-to-my-father/#comments</comments>
		<pubDate>Mon, 21 Jul 2008 04:00:55 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Quote]]></category>
		<category><![CDATA[Brevity]]></category>
		<category><![CDATA[Explaining Lisp]]></category>
		<category><![CDATA[Lambdas]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[Lisp Macros]]></category>
		<category><![CDATA[Self-Modifying code]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/?p=102</guid>
		<description><![CDATA[Anyone who read my post last week knows that I&#8217;ve been trying to learn Lisp in my free time. My Dad has also noticed, and he occasionally checks on my progress. A week or two ago, he threw me a curveball: &#8220;How&#8217;s it going? Do you understand it all yet?&#8221; &#8220;No. I&#8217;m making progress, though. [...]]]></description>
			<content:encoded><![CDATA[<p>Anyone who read my post last week knows that I&#8217;ve been trying to learn Lisp in my free time. My Dad has also noticed, and he occasionally checks on my progress.</p>
<p>A week or two ago, he threw me a curveball:</p>
<blockquote><p>&#8220;How&#8217;s it going? Do you understand it all yet?&#8221;</p>
<p>&#8220;No. I&#8217;m making progress, though. I&#8217;m probably not going to have this down for a while. It&#8217;s a completely different way of thinking from the programming I normally do.&#8221;</p>
<p>&#8220;How is it different?&#8221;</p></blockquote>
<p>I froze. He&#8217;s &#8220;Mr.-Fix-It,&#8221; and understands the rock quarry/asphault business inside and out. He&#8217;s very analytical, and it&#8217;s almost impossible to stump him with my favorite &#8220;Devil&#8217;s advocate&#8221; questions. However, aside from what I&#8217;ve told him, he just doesn&#8217;t know much about programming.</p>
<p>&#8220;Metaprogramming&#8221; and &#8220;first-class functions&#8221; wouldn&#8217;t have meant anything. &#8220;It lets you write programs faster&#8221; is a cop-out; he&#8217;s given me detailed explanations of his business. I wanted him to understand.</p>
<p>I was able to stammer out the fact that the language encourages breaking problems into smaller versions of the same problem (recursion), but that other programming languages also supported it.</p>
<p>I eventually told him that I hadn&#8217;t even thought about explaining the difference to a non-programmer.</p>
<p>&#8220;Well, if you&#8217;re ever able to come up with it, let me know.&#8221;</p>
<p>In college, I was a Computer Science tutor. I could explain most CS concepts that students saw in early C++ and Java courses to the layman on the street. However, I had <strong><span style="text-decoration: underline;"><em>nothing</em></span></strong> for explaining the difference between Lisp and C++ to him, which was a little scary. I spent some time dreaming up examples.</p>
<h2>Functions</h2>
<blockquote><p>All models are wrong, but some are useful.</p>
<p>~<a href="http://en.wikiquote.org/wiki/George_E._P._Box">George Box</a></p></blockquote>
<p>Abstract math notions are boring to most people, so I try to relate programming concepts to real-world items.</p>
<p>A fast-food restaurant is a great example of a function: An order and some money is input, and you get cheeseburgers, fries, a soda, and your change. Whether a person likes math or not, they know what a function is: you put something in, you get something out.</p>
<p>The idea is easily extensible to Object Oriented programming: all Burger Kings have orders, and you can place a specific order at an instance of a Burger King. A Burger King &#8220;is-a&#8221; fast food restaraunt.</p>
<p>I will use this metaphor to explain why Lisp is different from the programming I usually do (C++/Java/C#/Python).</p>
<h2>Lambdas</h2>
<p>Any restaraunt probably has a few different ways to order food: over the phone, at a drive-through window, at a counter, through a waiter, etc. However, there might be unofficial ways to order food: Bill Gates might write a letter requesting a buffet with a few hundreds slipped in as proof. Someone might tell the owner on his way to work that he&#8217;d like him to come back with a pizza.</p>
<p>The owner can easily define new ways to order food through a restaraunt.</p>
<p>Lisp, through &#8220;lambdas&#8221;, lets a programmer define new functions as easily as a restaraunt owner can devise new ways to order. The inputs and outputs are the same, but making new functions can have very low overhead compared to other programming languages.</p>
<h2>Brevity</h2>
<p>&#8220;Wiz Wit&#8221;.</p>
<p>This is my usual order at <a href="http://en.wikipedia.org/wiki/Pat%27s_King_of_Steaks">Pat&#8217;s</a> in Philly. With just two words, I get a cheesesteak with Cheez-Wiz and fried onions in less than 5 seconds. The system is designed to maximize the number of cheesesteaks output per hour: orders are short, and you usually get your cheesesteak before you&#8217;re done paying [and sometimes, before you're done speaking!]</p>
<p>This lesson can be applied to writing: It&#8217;s easier to convey a short thought. Unless you are Charles Dickens or Neal Stephenson, economy of language should be a goal.</p>
<p>Lisp&#8217;s syntax is very simple and short, so you can usually convey a thought in Lisp much quicker than you can convey a thought in most other programming languages.</p>
<h2>Macros</h2>
<p>An order can come in several different forms: it can be written, it can be gestured, it can be be spoken, and it can be implicit.</p>
<p>A lot of programming languages let you generalize the details of what an order can receive. Most orders are the same, so you can handle the contents the same even though the orders are different. In C++, you could even use &#8220;templates&#8221; to write code that generates code that handles this idea.</p>
<p>Lisp takes this idea all the way to its logical conclusion through &#8220;macros.&#8221; You can easily write functions that define orders. The difference is that you can easily do this at any scope!</p>
<p>If you notice that all fast food restaraunts are the same except for color scheme, specials, and slogans, it is easy to write functions that define new fast food chains. If you notice that your functions for defining fast food chains are similar to your functions for defining hardware chains, you can write functions that generate these producers.</p>
<p>Lisp lets you easily do this manufacturing on a level that is unimaginable with any other language. It may be possible, but nothing beats Lisp&#8217;s ease-of-use.</p>
<h2>Self-Modifying Code</h2>
<p>The metaphor breaks down here, and I won&#8217;t force it. However, the idea is simple when it is explained.</p>
<p>Most programming languages are designed to modify memory. They all store their information in memory, retrieve it, modify it, and write it to memory again.</p>
<p>Some programming languages try to hide the fact that they&#8217;re based on a memory-modification model, but they are extremely similar to languages that don&#8217;t hide it.</p>
<p>Lisp, however, is written to modify lists. Lisp is also written using lists, so a Lisp program can be programmed to modify itself.</p>
<h2>Conclusion</h2>
<p>This is just the tip of the iceberg! There are a lot more ideas that lay beneath the surface here, and you can bet that I&#8217;ll think about how to explain them to an educated adult. However, this should get someone with passing familiarity to programming to understand what makes Lisp stand out: ease-of-use and brevity.</p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=102&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2008/07/21/explaining-lisp-to-my-father/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Advantages and Problems of Executable Data</title>
		<link>http://www.jakevoytko.com/blog/2008/04/07/advantages-and-problems-of-executable-data/</link>
		<comments>http://www.jakevoytko.com/blog/2008/04/07/advantages-and-problems-of-executable-data/#comments</comments>
		<pubDate>Mon, 07 Apr 2008 04:00:38 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[code is data]]></category>
		<category><![CDATA[data is code]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[errors]]></category>
		<category><![CDATA[Executable data]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[logs]]></category>
		<category><![CDATA[Martian handsets]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/?p=68</guid>
		<description><![CDATA[I recently read two essays that dealt with the &#8220;Data as a Program&#8221; idea. It&#8217;s a nice idea overall, but there has to be downsides, right? I sat down for a few hours and riffed on the idea, and thought of a few problems that would need to be overcome by anyone using the &#8220;data [...]]]></description>
			<content:encoded><![CDATA[<p>I recently read two essays that dealt with the &#8220;Data as a Program&#8221; idea. It&#8217;s a nice idea overall, but there has to be downsides, right? I sat down for a few hours and riffed on the idea, and thought of a few problems that would need to be overcome by anyone using the &#8220;data as a program&#8221; paradigm on a large scale. But first, I want to bring you up to speed on some of the high notes hit by the essays.</p>
<h2>The Nature of Lisp</h2>
<p>First up is &#8220;<a href="http://www.defmacro.org/ramblings/lisp.html">The Nature of Lisp</a>&#8221; by Slava Akhmechet (passed along by my friend <a href="http://www.stephenlombardi.com/">Steve</a>). His essay is set up as an argument to use Lisp for the beginner. I found it pretty effective, as I decided to learn Lisp instead of Ruby this summer. That&#8217;s right, Ruby, you&#8217;ll just have to wait.</p>
<p>The essay looks at the design of <a href="http://en.wikipedia.org/wiki/Apache_Ant">Ant</a>, Java&#8217;s build tool. Ant is an XML-driven build system for the Java system that lets you specify how your Java applications are built. In essence, Slava made the following points:</p>
<ul>
<li>Ant is slowly marching (one by one) towards Turing Completeness.</li>
<li>The commands in Ant are being executed by <em>something</em>. It just happens to be Java.</li>
<li>Any XML is trivially convertible to Lisp.</li>
<li>Lisp has all of the same benefits as XML, but is a program and has extra benefits, including automatic data loading and metaprogramming facilities.</li>
<li>Lisp can be extended to other domain specific languages, and to know how to modify data within the language, you only have to learn a single language: Lisp.</li>
</ul>
<p>Developing the Ant language as an extension of Lisp is a nice idea, because Lisp solved all problems 154 years ago, back when cavemen wore bowties and were still allowed to ride dirigibles to work. As a result of decades of tweaking, Lisp is stable, fast, and elegant.</p>
<p>Storing your build scripts as Lisp is, in some respects, a very good solution to the problem. Since you are storing the data in what amounts to a Lisp data structure, tree commands can be executed on the data and transform it easily. This gives you the power of XSLT without any of the ugliness. Not only that, but since your data is already a program, the program can load itself into memory with a minimum of hassle. No more complicated parsing!</p>
<h2>The Emacs Problem</h2>
<p><a href="http://steve.yegge.googlepages.com/the-emacs-problem">&#8220;The Emacs Problem&#8221;</a> by Steve Yegge looks at the problem from the perspective of log parsing. Logs can be written as complicated text strings, or they can be written as XML. Both have their advantages, but in the end, having a standardized way to represent your data as a tree saves you from the trouble of modifying your complex string into a tree in order to do complex manipulations. If your data is in an easy-to-use tree, you can use tree traversing/modifying commands, which gives you more power.</p>
<p>Since your log can easily be written as XML, your log can easily be written as Lisp. Since your log is Lisp, it loads itself into memory and you don&#8217;t need to spend any extra time parsing it. Since your data is a program, it can know how to modify itself.</p>
<p>Neat, huh?</p>
<p>Steve takes the idea a step further in his section &#8220;Beyond Logs&#8221;.</p>
<blockquote><p>So Web pages have CSS, and JavaScript, and all this other hooey. It&#8217;s become so ugly that people don&#8217;t really write web pages anymore, not for production stuff. Nowadays people treat the morass of ancient, crufty Web technologies as a sort of assembly language. You write code to assemble your pages piecewise using PHP or XML/XSLT or Perl/Mason or Java/JSP or perhaps all of them in a giant ugly pipeline, which &#8220;compiles&#8221; down to an unreadable Web page format. Talk about fun!</p></blockquote>
<p>The solution?</p>
<blockquote><p>The whole nasty &#8220;configuration&#8221; problem becomes incredibly more convenient in the Lisp world.  No more stanza files, apache-config, .properties files, XML configuration files, Makefiles — all those lame, crappy, half-language creatures that you wish were executable, or at least loaded directly into your program without specialized processing.  I know, I know — everyone raves about the power of separating your code and your data.  That&#8217;s because they&#8217;re using languages that simply can&#8217;t do a good job of representing data as code.  But it&#8217;s what you really want, or all the creepy half-languages wouldn&#8217;t all evolve towards being Turing-complete, would they?</p>
<p>In fact, if you insist on code/data separation <em>and</em> you&#8217;re an advocate of OOP, then you&#8217;re talking out of both sides of your mouth. If your gut reaction to having log entries know how to transform or process themselves is &#8220;woah, that&#8217;s just <em>wrong</em>&#8220;, think again:  you&#8217;re imposing a world-view on the problem that&#8217;s not consistent with your notions of data encapsulation and active objects. This world-view dates back to ancient Unix and pre-Unix days.  But if you think about it, there&#8217;s no reason log entries or config files shouldn&#8217;t be executable and subclassable.  It might be better.</p>
<p>And what about, oh, web pages?  Or word-processor documents?  Well, you figure it out.</p></blockquote>
<p>Your webpage is a Lisp program. Your logfile is a Lisp program. All of your code is a Lisp program. Everything is a Lisp program. Hooray! Steve Yegge saved the internet!</p>
<h2>Security in the Small</h2>
<p>Everything we&#8217;ve discussed here is fine and dandy when you have your Lisp program read and execute Lisp data on your own Lisp machine. You can easily load log files, you can easily write log files, and you can easily manipulate log files. I want to look at another example, far more common than log files: web sites.</p>
<p>Let&#8217;s pretend the real world has two people, you and me. I ask you for your personal webpage, and you give me an executable file. It <em>could</em> be a webpage, but it could also be a horrible icky program that changes the contents of all of my Open Office documents to a copy of &#8220;<a href="http://www.youtube.com/watch?v=eBGIQ7ZuuiU">Never Gonna Give You Up</a>&#8221; by Rick Astley. I don&#8217;t trust you, reader.</p>
<p>OK, fine, realistically, we can&#8217;t let our web pages just do anything they feel like. After all, web pages come with Javascript, and Javascript can&#8217;t just wipe your hard drive the first time someone successfully cross-site scripts CNN. Nobody in their right mind would write a web browser that would just take an executable file that it&#8217;s been given and run it without even parsing it for harmful instructions.</p>
<p>&#8230; right?</p>
<p>&#8220;Of course you shouldn&#8217;t just execute a binary someone else gives you!&#8221; I hear you shouting. Who in their right mind would do that, right?</p>
<p>OK, so we know that web browsers should be written with a sandbox that prevents the evils of the world from doing whatever they want with your personal computer. But web browsers aren&#8217;t the only computer programs that use data. Let&#8217;s take Steve Yegge&#8217;s log file example. Let&#8217;s say that I write a program that uses log files. Since the data is code and knows how to modify itself, I can run it and have it entered into memory. That&#8217;s fine.</p>
<p>Let&#8217;s say that my program runs <strong><em>your</em></strong> log file. I need to keep it in the same kind of sandbox that web browsers use for very similar reasons. However, there is a new problem here. The set of coders writing &#8220;data is code&#8221;-style programs isn&#8217;t restricted to people with famous names.</p>
<p>Do you remember that guy from college that failed the intro course three times and still got a degree? He&#8217;ll be writing programs that execute data without checking it. Do you remember that guy in middle school who was willing to put anything in his mouth for a nickel? He&#8217;s now a highly-paid consultant for your company, and he&#8217;ll be writing programs that execute data without checking it.</p>
<p>OK, so this is a problem that is easily modularized and distributed. So is parsing, and many who don&#8217;t use automated parsing tools (and many who do) screw it up.</p>
<h2>Errors in the Large</h2>
<p>OK, so we now have a magical browser that won&#8217;t Rick-roll my whole hard drive when it requests a bad page. Now we can start sending our executable web pages to each other!</p>
<p>Hm, so you sent me a page that has an error on it. My browser has a few options.</p>
<ol>
<li>It can try to guess what you meant and display the page accordingly.</li>
<li>It can refuse to show me the page at all and give me a compilation error.</li>
<li>It can let me fix what is wrong with the file.</li>
<li>It can remove the error and show me what&#8217;s left of the page.</li>
</ol>
<p>Really, all of the same options that we are left with on current HTML web browsers. Javascript for the web has to warp in order to support the fact that Internet Explorer 6 supports a different flavor of Javascript than everyone else does. This could potentially do things to new executable formats &#8211;Lisp included&#8211; that you don&#8217;t want to see happen in your lifetime.</p>
<p>Imagine that we end up with the IE6 of Lisp browsers. Not only does this browser fail to correctly display correct Lisp, but it also has an extensive quirks mode that is very forgiving: it lets you also use C-style curly brackets for alternating parentheses groups, for instance. You know, just so the programmer can easily see where they end. This is also the web browser that everyone has by default, so it is the one that the unwashed masses are using in order to sink their teeth into Lisp.</p>
<p>The attack could come in any number of flavors, including &#8220;embrace and extend&#8221; and &#8220;ignore the agreed-upon standard&#8221;. There even may be types of ignorance that I didn&#8217;t think of. I&#8217;d bet on it. So we now have what amounts to a defective, entrenched Lisp interpreter. Not what the crowd is looking for.</p>
<h2>Conclusion</h2>
<p>Storing data as code is a powerful technique. Lisp, for example, has done this successfully since its inception, and it helps give the language some of its power.</p>
<p>Unfortunately, technique is imperfect when brought into the real world. Security is a huge concern, as &#8212; no offense&#8211; I don&#8217;t trust you. We can&#8217;t just treat data as Lisp programs and expect that people won&#8217;t try to take advantage of the fact that the files will be executed.</p>
<p>Not only that, but if this idea hits the big time for something like a web format, the people who design it have to be very careful about its release. We don&#8217;t want another <a href="http://www.joelonsoftware.com/items/2008/03/17.html">Martian Headsets</a> situation.</p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=68&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2008/04/07/advantages-and-problems-of-executable-data/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
