<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Blogging of Prolog</title>
	<atom:link href="http://prologomenon.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://prologomenon.wordpress.com</link>
	<description>And other logical excursions</description>
	<lastBuildDate>Sat, 28 Apr 2012 09:38:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='prologomenon.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>The Blogging of Prolog</title>
		<link>http://prologomenon.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://prologomenon.wordpress.com/osd.xml" title="The Blogging of Prolog" />
	<atom:link rel='hub' href='http://prologomenon.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Prologomenon is Taking a Hiatus</title>
		<link>http://prologomenon.wordpress.com/2012/03/31/prologomenon-is-taking-a-hiatus/</link>
		<comments>http://prologomenon.wordpress.com/2012/03/31/prologomenon-is-taking-a-hiatus/#comments</comments>
		<pubDate>Sat, 31 Mar 2012 09:59:02 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=651</guid>
		<description><![CDATA[As you&#8217;ve probably noticed by now, the frequency of updates have been rather low during the past months. And by rather low, I mean close to zero. And by close to zero, I mean zero. This stems from the fact that my ongoing master&#8217;s thesis (structural restrictions of a certain class of &#8220;easy&#8221; but NP-complete [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=651&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As you&#8217;ve probably noticed by now, the frequency of updates have been rather low during the past months. And by rather low, I mean close to zero. And by close to zero, I mean zero. This stems from the fact that my ongoing master&#8217;s thesis (structural restrictions of a certain class of &#8220;easy&#8221; but NP-complete constraint satisfaction problems) has nothing to do with logic programming. Hence I just don&#8217;t have the motivation or mental energy to simultaneously update the blog.</p>
<p>But fret not. I have every intention to keep the blog running once things have calmed down a bit. And if any of my learned readers have suggestions for upcoming topics I&#8217;m all ears. Just shoot me an email or write a comment.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/651/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/651/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=651&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2012/03/31/prologomenon-is-taking-a-hiatus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>
	</item>
		<item>
		<title>Meta-Programming in Prolog &#8211; Part 2</title>
		<link>http://prologomenon.wordpress.com/2011/11/09/meta-programming-in-prolog-part-2/</link>
		<comments>http://prologomenon.wordpress.com/2011/11/09/meta-programming-in-prolog-part-2/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 12:58:45 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Logic programming]]></category>
		<category><![CDATA[Logtalk]]></category>
		<category><![CDATA[Meta-programming]]></category>
		<category><![CDATA[Prolog]]></category>
		<category><![CDATA[Semantics]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=593</guid>
		<description><![CDATA[Here is the story thus far: a meta-program is a program that takes another program as input or output. Based on this idea we wrote an interpreter for a simple logic programming language and later extended it to build a proof tree. A proof of concept, if you will. Meta-interpreters have lost a lot of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=593&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Here is the story thus far: a meta-program is a program that takes another program as input or output. Based on this idea we wrote an interpreter for a simple logic programming language and later extended it to build a proof tree. A proof of concept, if you will. Meta-interpreters have lost a lot of steam in the last years. The reason being that they are just too hard to write in most popular programming languages. There&#8217;s no a priori reason that prevents us from writing a meta-interpreter in e.g. Python or Java, but the truth is that it&#8217;s such a lot of work that it&#8217;s not worth the trouble in most cases. The only exception that I can think of are integrated development environments which typically have at least some semantic awareness of the object language. But these languages doesn&#8217;t have a simple core and makes parsing awkward to say the least. In logic programming the situation is different. If an interpreter supports definite Horn clauses &#8212; facts and rules &#8212; and built-in operations it&#8217;s powerful enough to run quite a lot of real programs.</p>
<p>So what&#8217;s the purpose then? Is meta-programming just a sterile, academic exercise that has no place in real world software development? Since that was a rhetorical question, the answer is no. A resounding no! First, meta-interpreters are great for experimenting with new language features and implementation techniques. For instance we could ask ourself if it would be worthwhile to add support for new search rules in Prolog instead of defaulting to a simple depth-first search. Implementing a new search rule in a meta-interpreter can be done in a few hours, and the resulting program won&#8217;t be longer than perhaps a page of code (unless you screwed up, that is). Doing the same task in an imperative programming environment could take days or even weeks depending on the complexity of the existing code base. So meta-programming is useful for prototyping. What else? It can actually be a great aid in debugging. In the following sections we&#8217;re going to explain what debugging means in logic programming and develop a simple but functional system for squashing bugs. </p>
<h3>Algorithmic debugging</h3>
<p>Assume that we have a logic program <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> and a goal query <img src='http://s0.wp.com/latex.php?latex=%5Cleftarrow+G&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;leftarrow G' title='&#92;leftarrow G' class='latex' />. Sterling and Shapiro cites three possible bugs in The Art of Prolog:</p>
<ol>
<li>The interpreter could fail to terminate.</li>
<li>The interpreter could return a false solution <img src='http://s0.wp.com/latex.php?latex=G%5Ctheta&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G&#92;theta' title='G&#92;theta' class='latex' />. (incorrectness)</li>
<li>The interpreter could fail to return a true solution <img src='http://s0.wp.com/latex.php?latex=G%5Ctheta&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G&#92;theta' title='G&#92;theta' class='latex' />. (insufficiency)</li>
</ol>
<p>Since the first problem is undecidable in general we shall focus on the latter two. But first we need to decide what the words true and false means in this context, and in order to do that some remarks about the semantics of logic programs have to be made. If you&#8217;re feeling a bit rusty, I urge you to read up a bit on Herbrand models. <a href="http://en.wikipedia.org/wiki/Herbrand_interpretation">Wikipedia</a> and my own <a title="A Gentle Introduction to Herbrand Models" href="http://prologomenon.wordpress.com/2011/02/12/a-gentle-introduction-to-herbrand-models/">earlier post</a> are both good starting points. The basic idea is fortunately rather simple. Logic formulas and programs can be viewed as specifications of models. A model is an interpretation in which the program is true. In general there are many, infinitely many, models of any given definite logic program. Which one should we choose? In a model we are free to reinterpret the non-logical vocabulary in any way we see fit. Consider the following logic program:</p>
<p><img src='http://s0.wp.com/latex.php?latex=natural%28zero%29.&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural(zero).' title='natural(zero).' class='latex' /><br />
<img src='http://s0.wp.com/latex.php?latex=natural%28s%28X%29%29+%5Cleftarrow+natural%28X%29.&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural(s(X)) &#92;leftarrow natural(X).' title='natural(s(X)) &#92;leftarrow natural(X).' class='latex' /></p>
<p>It can be seen as a specification of either the set <img src='http://s0.wp.com/latex.php?latex=%5C%7Bnatural%280%29%2C+natural%281%29%2C+%5Cldots%5C%7D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;{natural(0), natural(1), &#92;ldots&#92;}' title='&#92;{natural(0), natural(1), &#92;ldots&#92;}' class='latex' /> or the set <img src='http://s0.wp.com/latex.php?latex=%5C%7Bnatural%28zero%29%2C+natural%28s%28zero%29%29%2C+%5Cldots+%5C%7D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;{natural(zero), natural(s(zero)), &#92;ldots &#92;}' title='&#92;{natural(zero), natural(s(zero)), &#92;ldots &#92;}' class='latex' />. Notice the subtle difference. The latter model is simpler in the sense that it doesn&#8217;t take us outside the domain of the textual representation of the program itself. Such models are known as Herbrand models. Could we be so lucky that Herbrand models are the only kind of models that we need to pay attention to? This is indeed the case. If a logic program has a model then it also has a Herbrand model. But we still need to pick and choose between the infinitely many Herbrand models. The intuition is that a model of a logic program shouldn&#8217;t say more than it have to. Hence we choose the smallest Herbrand model as the meaning of a logic program. Or, put more succinct, the intersection of all Herbrand models. For a logic program <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' />, let <img src='http://s0.wp.com/latex.php?latex=M_P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='M_P' title='M_P' class='latex' /> denote the smallest Herbrand model of <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' />.</p>
<p>This is good news since we now know that every well-formed logic program has a meaning. Let&#8217;s return to the question of false solutions. This notion is only relevant if the programmer has an <em>intended</em> meaning that differs from the <em>actual</em> meaning of the program. In all but the most trivial programming tasks this happens all the time. An intended meaning <img src='http://s0.wp.com/latex.php?latex=I_P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='I_P' title='I_P' class='latex' /> of a logic program <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> is the set of ground goals for which the program should succeed. Note the &#8220;should&#8221;. If we briefly return to <img src='http://s0.wp.com/latex.php?latex=natural%2F1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural/1' title='natural/1' class='latex' />, the intended meaning is nothing else than the actual meaning, i.e. the set <img src='http://s0.wp.com/latex.php?latex=%5C%7Bnatural%28zero%29%2C+natural%28s%28zero%29%29%2C+%5Cldots+%5C%7D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;{natural(zero), natural(s(zero)), &#92;ldots &#92;}' title='&#92;{natural(zero), natural(s(zero)), &#92;ldots &#92;}' class='latex' />. With this terminology it&#8217;s possible to give a precise definition of incorrectness and insufficiency of a logic program <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' />:</p>
<ol>
<li><img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> is <em>incorrect</em> iff <img src='http://s0.wp.com/latex.php?latex=M_P+%5Cnot%5Csubseteq+I_P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='M_P &#92;not&#92;subseteq I_P' title='M_P &#92;not&#92;subseteq I_P' class='latex' />.</li>
<li><img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> is <em>insufficient</em> iff <img src='http://s0.wp.com/latex.php?latex=I_P+%5Cnot%5Csubseteq+M_P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='I_P &#92;not&#92;subseteq M_P' title='I_P &#92;not&#92;subseteq M_P' class='latex' />.</li>
</ol>
<p>With these definitions we see that the <img src='http://s0.wp.com/latex.php?latex=natural%2F1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural/1' title='natural/1' class='latex' /> program is neither incorrect nor insufficient. But let&#8217;s introduce some bugs in it:</p>
<div>
<p><img src='http://s0.wp.com/latex.php?latex=natural1%28%5C_%29.&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural1(&#92;_).' title='natural1(&#92;_).' class='latex' /><br />
<img src='http://s0.wp.com/latex.php?latex=natural1%28s%28X%29%29+%5Cleftarrow+natural1%28X%29.&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural1(s(X)) &#92;leftarrow natural1(X).' title='natural1(s(X)) &#92;leftarrow natural1(X).' class='latex' /></p>
</div>
<p><img src='http://s0.wp.com/latex.php?latex=natural2%28zero%29.&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural2(zero).' title='natural2(zero).' class='latex' /><br />
<img src='http://s0.wp.com/latex.php?latex=natural2%28s%28X%29%29+%5Cleftarrow+natural2%28s%28X%29%29.&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural2(s(X)) &#92;leftarrow natural2(s(X)).' title='natural2(s(X)) &#92;leftarrow natural2(s(X)).' class='latex' /></p>
<p>Can you spot them? <img src='http://s0.wp.com/latex.php?latex=natural1%2F1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural1/1' title='natural1/1' class='latex' /> is incorrect since the base clause is too inclusive. <img src='http://s0.wp.com/latex.php?latex=M_P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='M_P' title='M_P' class='latex' /> is not a subset of <img src='http://s0.wp.com/latex.php?latex=I_P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='I_P' title='I_P' class='latex' /> since e.g. the element <img src='http://s0.wp.com/latex.php?latex=natural%28-1%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural(-1)' title='natural(-1)' class='latex' /> is not a member of <img src='http://s0.wp.com/latex.php?latex=I_P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='I_P' title='I_P' class='latex' />. In the same vein, <img src='http://s0.wp.com/latex.php?latex=natural2%2F1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural2/1' title='natural2/1' class='latex' /> is insufficient since it&#8217;s equivalent to just <img src='http://s0.wp.com/latex.php?latex=natural2%28zero%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='natural2(zero)' title='natural2(zero)' class='latex' />.</p>
<p>Quite a lot of legwork to explain something which is actually rather simple! What remains is to put everything in practice. Due to space constraints we&#8217;ll focus on the incorrectness problem.</p>
<h3>Incorrectness</h3>
<p>A logic program <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> is incorrect if it gives solutions that are not included in the intended model. In a real-world situation this means that the programmer has found a goal which the program should reject, but it doesn&#8217;t, and hence it contains at least one bug. The purpose is to find the part in the program that is responsible for the bug. In logic programming terms this is of course a clause. A clause <img src='http://s0.wp.com/latex.php?latex=A+%5Cleftarrow+B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A &#92;leftarrow B' title='A &#92;leftarrow B' class='latex' /> is false iff <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> is true and <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> is false. The purpose of the algorithm is to traverse the proof tree and find such a clause. With this in mind we can at least write the top-level predicate:</p>
<p><pre class="brush: plain;">
   false_solution(Goal, Clause) :-
       %Build a proof tree.
       interpreter::prove(Goal, Tree),
       %Find a false clause.
       false_goal(Tree, Clause).
</pre></p>
<p>Well, that wasn&#8217;t too hard. What about <img src='http://s0.wp.com/latex.php?latex=false%5C_goal%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='false&#92;_goal/2' title='false&#92;_goal/2' class='latex' />? The tree is of the form <img src='http://s0.wp.com/latex.php?latex=A+%5Cleftarrow+B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A &#92;leftarrow B' title='A &#92;leftarrow B' class='latex' />. Hence there are two cases: either <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> is false or it&#8217;s true. If it&#8217;s false, then we must continue the search in <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />. If it&#8217;s true, then the current clause is the clause that we&#8217;re looking for. To determine whether <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> is false we need an auxiliary predicate, <img src='http://s0.wp.com/latex.php?latex=false%5C_conjunction%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='false&#92;_conjunction/2' title='false&#92;_conjunction/2' class='latex' />, where the first argument is the conjunction of nodes and the second argument is the false clause (if it exists).</p>
<p><pre class="brush: plain;">
   false_goal((A :- B), Clause) :-
       (    false_conjunction(B, Clause) -&gt;
            true
       ;    Clause = (A :- B1),
            %Necessary since we don't want the whole tree.
            extract_body(B, B1)
       ).
</pre></p>
<p>By the way, this is a fine example of top-down development. In each step we&#8217;re breaking the original problem into easier problems and assume that we&#8217;re able to solve them later. <img src='http://s0.wp.com/latex.php?latex=false%5C_conjunction%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='false&#92;_conjunction/2' title='false&#92;_conjunction/2' class='latex' /> is a bit trickier. The first argument is a conjunction of nodes of the form <img src='http://s0.wp.com/latex.php?latex=A+%5Cleftarrow+B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A &#92;leftarrow B' title='A &#92;leftarrow B' class='latex' />. Just like before there are two cases since <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> is either false or true. If it&#8217;s true, then we move on to the rest of the nodes. If it&#8217;s false, then we&#8217;d like to know whether <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> is true or false. Luckily we&#8217;ve already solved this problem before &#8212; a call to <img src='http://s0.wp.com/latex.php?latex=false%5C_goal%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='false&#92;_goal/2' title='false&#92;_goal/2' class='latex' /> will do the trick just fine.</p>
<p><pre class="brush: plain;">
   false_conjunction(((A :- B), _Bs), Clause) :-
       query_goal(A, false),
       !,
       false_goal((A :- B), Clause).
   %Almost the same case as above, but with only one element.
   false_conjunction((A :- B), Clause) :-
       query_goal(A, false),
       !,
       false_goal((A :- B), Clause).
   false_conjunction((_A, As), Clause) :-
       %A is implicitly true.
       false_conjunction(As, Clause).
</pre></p>
<p>Only the most perplexing predicate remains: <img src='http://s0.wp.com/latex.php?latex=query%5C_goal%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='query&#92;_goal/2' title='query&#92;_goal/2' class='latex' />. The second argument is <img src='http://s0.wp.com/latex.php?latex=true&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='true' title='true' class='latex' /> if <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> is true and <img src='http://s0.wp.com/latex.php?latex=false&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='false' title='false' class='latex' /> if it&#8217;s false. How can we know this? This is where the programmer&#8217;s intended model enters the picture. For now, we&#8217;re just going to use her/him as an oracle and assume that all choices are correct. The predicate is then trivial to write:</p>
<p><pre class="brush: plain;">
   query_goal(G, Answer) :-
       %Change later.
       write('Is the goal '),
       write(G),
       write(, ' true?'),
       nl,
       read(Answer).
</pre></p>
<p>In essence the user will be asked a series of questions during a session with the program. Depending on the answers, i.e. the intended model, the program will dive deeper and deeper into the proof tree in order to find the troublesome clause. As an example, here&#8217;s an append program where the base case is wrong:</p>
<p><pre class="brush: plain;">
append([_X], Ys, Ys) :- true.
append([X|Xs], Ys, [X|Zs]) :-
    append(Xs, Ys, Zs).
</pre></p>
<p>And the session with the program would look like this:</p>
<blockquote>
<pre>[1]  ?- debugging::false_solution(append([a,b,c], [d,e], Xs), Clause).
Is the goal append([b,c],[d,e],[b,d,e]) true?
|: false.
Is the goal append([c],[d,e],[d,e]) true?
|: false.
Xs = [a, b, d, e],
Clause = (append([c], [d, e], [d, e]):-true)</pre>
</blockquote>
<p>And we clearly see that it&#8217;s the base case that&#8217;s wrong.</p>
<h3>Summary</h3>
<p>The algorithm was taken from The Art of Prolog. Some simplifying assumptions have been made. Among other things there&#8217;s currently no support for built-in operations. This is rather easy to fix, however. A more serious question is if it would be possible to minimize the role of the oracle, since it&#8217;s now queried every time a decision needs to be made. There are two techniques for coping with this. Either we do a smarter traversal of the proof tree with e.g. divide and conquer, or we find a way to approximate the intended model of the program without the use of an oracle.</p>
<h3>Source code</h3>
<p>The source code is available at <a href="https://gist.github.com/1351227">https://gist.github.com/1351227</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/593/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/593/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/593/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/593/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/593/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/593/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/593/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/593/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/593/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/593/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/593/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/593/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/593/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/593/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=593&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/11/09/meta-programming-in-prolog-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>
	</item>
		<item>
		<title>Meta-Programming in Prolog &#8211; Part 1</title>
		<link>http://prologomenon.wordpress.com/2011/11/01/meta-programming-in-prolog-part-1/</link>
		<comments>http://prologomenon.wordpress.com/2011/11/01/meta-programming-in-prolog-part-1/#comments</comments>
		<pubDate>Tue, 01 Nov 2011 11:35:03 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Logic programming]]></category>
		<category><![CDATA[Logtalk]]></category>
		<category><![CDATA[Meta-programming]]></category>
		<category><![CDATA[Prolog]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=530</guid>
		<description><![CDATA[Introduction Meta-programming is part of the folklore in Prolog, and is in general a rather old concept with roots tracing back to at least the 50&#8242;s. To give a definition that captures all the relevant concepts is outside the scope of this introductory text, but I shall at least provide some pointers that&#8217;ll be useful [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=530&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Meta-programming is part of the folklore in Prolog, and is in general a rather old concept with roots tracing back to at least the 50&#8242;s. To give a definition that captures all the relevant concepts is outside the scope of this introductory text, but I shall at least provide some pointers that&#8217;ll be useful later on. Programs are useful in many different domains. We might be working with numbers, with graphs, with lists or with any other data structure. What happens when the domain is another programming language? Well, nothing, really, from the computer&#8217;s point of view there&#8217;s no difference between this scenario and the former. But conceptually speaking we&#8217;re writing programs that are themselves working with programs. Hence the word &#8220;meta&#8221; in meta-programming. A compiler or interpreter is by this definition a meta-program. But in logic programming we&#8217;re usually referring to something more specific when we&#8217;re talking about meta-programming, namely programs that takes other logic programs as data. Since Prolog is a homoiconic language there&#8217;s also nothing that stops us from writing programs that takes other Prolog programs as data, but even though there&#8217;s a subtle distinction between this and the former scenario they are often referred to as one and the same. So, to summarize, when we&#8217;re talking about meta-programs in logic programming we&#8217;re quite often referring to <em>Prolog</em> <em>programs</em> that uses <em>logic programs</em> as data.</p>
<p>The road map for this post is to see some examples of meta-interpreters in Prolog. Then we&#8217;re going to use the interpreters to aid program development with a technique known as <em>algorithmic debugging</em>. But enough talk, let&#8217;s do this!</p>
<h3>Meta-interpreters</h3>
<p>There&#8217;s still ample room for confusion regarding the word &#8220;meta&#8221; in meta-interpreter. I shall use the word whenever I refer to an interpreter for a logic programming language, even though this is not factually correct since one usually demands that the object language and the meta language are one and the same. That is: we write an interpreter <em>for</em> Prolog <em>in</em> Prolog. There are good reasons for not doing this. Prolog is a large and unwieldy language with many impure features such as cut, IO, assert/retract and so on, and when we&#8217;re working with meta-interpreters we&#8217;re often only interested in a small, declarative part of the language. Hence we shall restrict our focus to a programming language akin to pure Prolog which is basically just a set of Horn clauses/rules.</p>
<p>Even though we still haven&#8217;t decided the syntax for the object language we know that we must represent at least two things: facts and rules. Since a fact <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> is equivalent to the rule <img src='http://s0.wp.com/latex.php?latex=A+%5Cleftarrow+true&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A &#92;leftarrow true' title='A &#92;leftarrow true' class='latex' /> we can store these in the same manner. Assume that <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> is a definite logic program. How should we represent it? As a list or a search tree? This could be a good approach if we were interested in implementing dynamic predicates in a declarative way, but since <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> is static it&#8217;s much easier to just use the database and store everything as facts. For every rule <img src='http://s0.wp.com/latex.php?latex=A+%5Cleftarrow+B_1%2C+...%2C+B_n+%5Cin+P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A &#92;leftarrow B_1, ..., B_n &#92;in P' title='A &#92;leftarrow B_1, ..., B_n &#92;in P' class='latex' />, represent it as the fact <img src='http://s0.wp.com/latex.php?latex=rule%28A%2C+%5BB_1%2C+...%2C+B_n%5D%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='rule(A, [B_1, ..., B_n])' title='rule(A, [B_1, ..., B_n])' class='latex' />. If a rule only has the single atom <img src='http://s0.wp.com/latex.php?latex=true&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='true' title='true' class='latex' /> in its body, i.e. it is a fact, then the second argument is the empty list. Obviously this is just one of many possible representations, but it&#8217;s simple to implement and work with.</p>
<p>As an example, here&#8217;s how we would write <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' />:</p>
<p><pre class="brush: plain;">
rule(append([], Ys, Ys), []).
rule(append([X|Xs], Ys, [X|Zs]),[append(Xs, Ys, Zs)]).
</pre></p>
<p>Simple, but not exactly pleasing to the eye. Fortunately it&#8217;s easy to add some syntactic sugar with the help of Prolog&#8217;s term expansion mechanism. Instead of directly using <img src='http://s0.wp.com/latex.php?latex=rule%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='rule/2' title='rule/2' class='latex' /> we can rewrite <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> as:</p>
<p><pre class="brush: plain;">
append([], Ys, Ys) :- true.
append([X|Xs], Ys, [X|Zs]) :-
    append(Xs, Ys, Zs).
</pre></p>
<p>And then define a suitable expansion object so that we end up with a set of <img src='http://s0.wp.com/latex.php?latex=rule%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='rule/2' title='rule/2' class='latex' /> facts. This is a rather mundane and not very exciting programming task and hence omitted. Now on to the interpreter. It will be defined by a set of <img src='http://s0.wp.com/latex.php?latex=prove%2F1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='prove/1' title='prove/1' class='latex' /> clauses where the single argument is a list of goals. If you&#8217;ve never seen a meta-interpreter in Prolog before, you&#8217;re probably in for some serious disappointment since the program is so darn simple. So simple that a first reaction might be that it can&#8217;t possibly do anything useful. This first impression is wrong, however, since it&#8217;s easy to increase the granularity of the interpreter by implementing features instead of borrowing them from the Prolog system.</p>
<p>As mentioned the interpreter takes a list of goals as argument. This means that there&#8217;s a base case and a recursive case. In the base case of the empty list we are done. In the recursive case we have a list of the form <img src='http://s0.wp.com/latex.php?latex=%5BG%7CGs%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[G|Gs]' title='[G|Gs]' class='latex' /> where <img src='http://s0.wp.com/latex.php?latex=G&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G' title='G' class='latex' /> is the first goal that shall be proven. How do we prove <img src='http://s0.wp.com/latex.php?latex=G&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G' title='G' class='latex' /> then? By looking if there&#8217;s a corresponding rule <img src='http://s0.wp.com/latex.php?latex=rule%28A%2C+%5BB_1%2C+...%2C+B_n%5D%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='rule(A, [B_1, ..., B_n])' title='rule(A, [B_1, ..., B_n])' class='latex' /> where <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=G&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G' title='G' class='latex' /> are unifiable with mgu <img src='http://s0.wp.com/latex.php?latex=%5Ctheta&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;theta' title='&#92;theta' class='latex' /> and recursively prove <img src='http://s0.wp.com/latex.php?latex=%28%5BB_1%2C+...%2C+B_n%7CGs%5D%29+%5Ctheta&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='([B_1, ..., B_n|Gs]) &#92;theta' title='([B_1, ..., B_n|Gs]) &#92;theta' class='latex' />. In almost any other language this would be considerable work, but since Prolog is a logic programming language we already know how to do unification. Thus we end up with:</p>
<p><pre class="brush: plain;">
%Initialize the goal list with G.
prove(G) :-
   prove1([G]).

prove1([]).
prove1([G|Gs]) :-
   rule(G, B),
   prove1(B),
   prove1(Gs).
</pre></p>
<p>This is a prime example of declarative programming. We&#8217;ve only described what it means for a conjunction of goals to be provable and left the rest to the Prolog system. If you&#8217;re unsure why or how the interpreter works I urge you to try it for yourself.</p>
<h3>Extensions</h3>
<p>To prove that I wasn&#8217;t lying before I shall illustrate some neat extensions to the bare-bone interpreter. Strictly speaking we don&#8217;t really need anything else since the language is already Turing complete. It&#8217;s e.g. trivial to define predicates that define and operate on the natural numbers. For example:</p>
<p><pre class="brush: plain;">
nat(zero) :- true.
nat(s(X)) :- nat(X).

add(zero, Y, Y) :- true.
add(s(X), Y, s(Z)) :-
   add(X, Y, Z).
</pre></p>
<p>But since these operations can be implemented much more efficiently on any practical machine it&#8217;s better to borrow the functionality. Hence we shall define a set of built-in predicates that are proved by simply executing them. The easiest way is to add a <img src='http://s0.wp.com/latex.php?latex=rule%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='rule/2' title='rule/2' class='latex' /> definition for every built-in predicate.</p>
<p><pre class="brush: plain;">
rule(rule(A, B), []) :-
    rule(A, B).
rule((X is Y), []) :-
    X is Y.
</pre></p>
<p>Why the first clause? So that we can facilitate meta-programming and use <img src='http://s0.wp.com/latex.php?latex=rule%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='rule/2' title='rule/2' class='latex' /> in our object language. I mentioned earlier that the interpreter as defined is not really a meta-interpreter in the strict sense of the word, and that Prolog is such a large language that writing meta-interpreters for it is probably not worth the hassle. But now we have a very restricted yet powerful language. Can we write a real meta-interpreter in that language? Yes! Actually it&#8217;s hardly any work at all since we already have the source code for the old interpreter.</p>
<p><pre class="brush: plain;">
prove(G) :-
    prove1([G]).

prove1([]) :- true.
prove1([G|Gs]) :-
    rule(G, B),
    prove1(B),
    prove1(Gs).
</pre></p>
<p>Glorious. Perhaps not very practical, but glorious.</p>
<h3>Building a proof tree</h3>
<p>When our interpreter gives an answer it doesn&#8217;t provide any indication as to why that answer was produced. Perhaps the answer is in fact wrong and we want to localize the part of the code that is responsible for the error. The first step in this process is to build a proof tree. A proof tree for a goal <img src='http://s0.wp.com/latex.php?latex=%5Cleftarrow+G&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;leftarrow G' title='&#92;leftarrow G' class='latex' /> and logic program <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> is a tree where 1) the root is labeled <img src='http://s0.wp.com/latex.php?latex=G&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G' title='G' class='latex' />, and  2) each node has a child for every subgoal with respect to <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' />. Hence the proof tree is more or less a representation of a sequence of trace steps.</p>
<p>It might sound like a complex task, but it&#8217;s really not. All we need is to extend the <img src='http://s0.wp.com/latex.php?latex=prove%2F1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='prove/1' title='prove/1' class='latex' /> predicate with an additional argument for the proof tree. In the base case of the empty list the tree contains the single node <img src='http://s0.wp.com/latex.php?latex=true&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='true' title='true' class='latex' />. If <img src='http://s0.wp.com/latex.php?latex=%5BG%7CGs%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[G|Gs]' title='[G|Gs]' class='latex' /> are the current goals then we prove <img src='http://s0.wp.com/latex.php?latex=G&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G' title='G' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=Gs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Gs' title='Gs' class='latex' /> and builds a proof tree from the recursive goals.</p>
<p><pre class="brush: plain;">
prove(G, T) :-
    prove1([G], T).

prove1([], true).
prove1([G|Gs], ((G :- T1), T2)) :-
    rule(G, B),
    prove1(B, T1),
    prove1(Gs, T2).
</pre></p>
<p>And when called with <img src='http://s0.wp.com/latex.php?latex=G+%3D+append%28%5Ba%2Cb%5D%2C+%5Bc%2Cd%5D%2C+Xs%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G = append([a,b], [c,d], Xs)' title='G = append([a,b], [c,d], Xs)' class='latex' /> the resulting tree looks like this:</p>
<p><pre class="brush: plain;">
?- interpreter::prove(append([a,b], [c,d], Xs), T).
Xs = [a, b, c, d],
T = ((append([a, b], [c, d], [a, b, c, d]):- (append([b], [c, d], [b, c, d]):- (append([], [c, d], [c, d]):-true), true), true), true)
</pre></p>
<p>NB: this tree has a lot of redundant <img src='http://s0.wp.com/latex.php?latex=true&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='true' title='true' class='latex' /> entries. How can we fix this?</p>
<h3>Summary</h3>
<p>We&#8217;re now able to build proof trees. In the next entry we&#8217;re going to use them to localize errors in logic programs.</p>
<p>For a good discussion of meta-interpreters in Prolog the reader should turn to <em>The Craft of Prolog</em> by <em>Richard O&#8217;Keefe</em>. This post was just the tip of the iceberg. Another interesting subject is to experiment with different search rules, and for this I shamelessly promote my own bachelor&#8217;s thesis which is available at <a href="http://www.diva-portal.org/smash/record.jsf?searchId=1&amp;pid=diva2:325247">http://www.diva-portal.org/smash/record.jsf?searchId=1&amp;pid=diva2:325247</a>.</p>
<h3>Source code</h3>
<p>The source code is available at <a href="https://gist.github.com/1330321">https://gist.github.com/1330321</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/530/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/530/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/530/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/530/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/530/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/530/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/530/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/530/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/530/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/530/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/530/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/530/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/530/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/530/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=530&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/11/01/meta-programming-in-prolog-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>
	</item>
		<item>
		<title>Arcane Abuses of append</title>
		<link>http://prologomenon.wordpress.com/2011/10/24/arcane-abuses-of-append/</link>
		<comments>http://prologomenon.wordpress.com/2011/10/24/arcane-abuses-of-append/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 13:47:40 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Logic programming]]></category>
		<category><![CDATA[Prolog]]></category>
		<category><![CDATA[Ramblings]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=491</guid>
		<description><![CDATA[First I should point out that the following predicates hardly qualify as arcane, and they&#8217;re not really that abusive either. But they do use append, and one out of three isn&#8217;t so bad after all? is one of Prolog&#8217;s most useful predicates and is often one of the list predicates first taught to students. Beginners, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=491&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>First I should point out that the following predicates hardly qualify as arcane, and they&#8217;re not really that abusive either. But they do use append, and one out of three isn&#8217;t so bad after all? <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> is one of Prolog&#8217;s most useful predicates and is often one of the list predicates first taught to students. Beginners, and especially those familiar with other programming languages, sometimes have a hard time recognizing the multiple usages of the predicate however. Just for reference and to make sure that we&#8217;re on the same page, the usual definition goes like this:</p>
<p><pre class="brush: plain;">

   append([], Ys, Ys).
   append([X|Xs], Ys, [X|Zs]) :-
        append(Xs, Ys, Zs).

</pre></p>
<p>Nothing fanciful. Just a standard recursive predicate which holds if <img src='http://s0.wp.com/latex.php?latex=Zs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Zs' title='Zs' class='latex' /> is the list obtained when appending all the elements of <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> with all the elements of <img src='http://s0.wp.com/latex.php?latex=Ys&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys' title='Ys' class='latex' />. So when should we use this predicate? When we want to append two lists? No! Upon years of using Prolog I don&#8217;t think I&#8217;ve used <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> for this purpose in a serious program even once. The reason being that difference lists are usually a much better choice in these instances since they can be appended in constant instead of linear time. So let&#8217;s try to figure out some other usages.</p>
<p><img src='http://s0.wp.com/latex.php?latex=member%28X%2C+Xs%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='member(X, Xs)' title='member(X, Xs)' class='latex' /> is true if <img src='http://s0.wp.com/latex.php?latex=X&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='X' title='X' class='latex' /> is a member of the list <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' />. It&#8217;s of course not hard to write this as a recursive predicate as we did with <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' />, but why bother if there&#8217;s an easier way? So let&#8217;s solve it with <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> instead. Upon a first inspection it might not look like they have anything to do with each other. How can we find an element in a list by appending two lists? The answer is actually pretty simple. We know that we take a list, <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' />, as argument. Can we find two other lists such that they give <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> when appended? Of course. Just call <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> with <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> as the third argument. Remember that <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> is a <em>relation</em> and not a <em>function</em>:</p>
<blockquote><p>?- Xs = [a,b,c], append(A, B, Xs).<br />
Xs = [a, b, c],<br />
A = [],<br />
B = [a, b, c] n<br />
n<br />
Xs = [a, b, c],<br />
A = [a],<br />
B = [b, c] n<br />
n<br />
Xs = [a, b, c],<br />
A = [a, b],<br />
B = [c] n<br />
n<br />
Xs = A, A = [a, b, c],<br />
B = [] n<br />
n<br />
false.</p></blockquote>
<p>That was the first step. Now let&#8217;s find an interpretation of membership that can be cast in terms of these three lists. How about this: <img src='http://s0.wp.com/latex.php?latex=X&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='X' title='X' class='latex' /> is a member of <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> if <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> can be divided into two parts, <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />, such that <img src='http://s0.wp.com/latex.php?latex=X&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='X' title='X' class='latex' /> comes between <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />. Put into code this is:</p>
<p><pre class="brush: plain;">
    member(X, Xs) :-
        append(_A, [X|_B], Xs).
</pre></p>
<p>Very easy once you know the trick, but difficult if one is afraid of using <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> as a relation instead of a function. A similar problem is the sublist problem: given a list <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' />, is <img src='http://s0.wp.com/latex.php?latex=Ys&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys' title='Ys' class='latex' /> a sublist of <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' />? Again it&#8217;s not hard to imagine how a recursive version would look, but perhaps we can find an easier solution with the help of <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' />. A sublist is a continuous subsequence. This can be expressed in terms of three lists: <img src='http://s0.wp.com/latex.php?latex=Ys&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys' title='Ys' class='latex' /> is sublist of <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> if there exists two lists, <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />, such that <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> appended with <img src='http://s0.wp.com/latex.php?latex=Ys&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys' title='Ys' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> results in <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' />. That was quite a mouthful, but in essence it&#8217;s the same thing as we did with <img src='http://s0.wp.com/latex.php?latex=member%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='member/2' title='member/2' class='latex' /> with the difference being that we&#8217;re looking for a list instead of a single element. Assume that we had the predicate <img src='http://s0.wp.com/latex.php?latex=append%2F4&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/4' title='append/4' class='latex' />. Then sublist could be solved as:</p>
<p><pre class="brush: plain;">
sublist(Xs, Ys) :-
    append(_A, Ys, _B, Xs).
</pre></p>
<p>Alas, since we don&#8217;t have such a predicate we&#8217;re going to use <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> two times instead. First <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> is divided into <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />. Then we find the sublist <img src='http://s0.wp.com/latex.php?latex=Ys&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys' title='Ys' class='latex' /> by saying that <img src='http://s0.wp.com/latex.php?latex=Ys&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys' title='Ys' class='latex' /> is a suffix of <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />.</p>
<p><pre class="brush: plain;">
    sublist(Xs, Ys) :-
        append(_A, B, Xs),
        append(_, Ys, B).
</pre></p>
<p>It should be noted that this solution gives rise to many duplicate answers. Why? Assume that <img src='http://s0.wp.com/latex.php?latex=Xs+%3D+%5Ba%2Cb%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs = [a,b]' title='Xs = [a,b]' class='latex' />. Then the answer <img src='http://s0.wp.com/latex.php?latex=Ys+%3D+%5Bb%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys = [b]' title='Ys = [b]' class='latex' /> can be found by first binding <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> to <img src='http://s0.wp.com/latex.php?latex=%5Ba%2Cb%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[a,b]' title='[a,b]' class='latex' /> and then <img src='http://s0.wp.com/latex.php?latex=Ys&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys' title='Ys' class='latex' /> to the prefix <img src='http://s0.wp.com/latex.php?latex=%5Bb%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[b]' title='[b]' class='latex' /> of this list. Or it can be found by binding <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> to <img src='http://s0.wp.com/latex.php?latex=%5Bb%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[b]' title='[b]' class='latex' /> and then binding <img src='http://s0.wp.com/latex.php?latex=Ys&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ys' title='Ys' class='latex' /> to the prefix <img src='http://s0.wp.com/latex.php?latex=%5Bb%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[b]' title='[b]' class='latex' /> of <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />. This is a bummer since we&#8217;re only interested in one of these answers. The implementation of an optimized version is left as an exercise to the reader.</p>
<p><img src='http://s0.wp.com/latex.php?latex=select%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='select/3' title='select/3' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=last%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='last/2' title='last/2' class='latex' /> and other basic list processing predicates can be implemented in essentially the same manner. As a last example we&#8217;re going to implement <img src='http://s0.wp.com/latex.php?latex=nth%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='nth/3' title='nth/3' class='latex' /> with <img src='http://s0.wp.com/latex.php?latex=append%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='append/3' title='append/3' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=length%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='length/2' title='length/2' class='latex' />. <img src='http://s0.wp.com/latex.php?latex=nth%28X%2C+Xs%2C+N%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='nth(X, Xs, N)' title='nth(X, Xs, N)' class='latex' /> is true if <img src='http://s0.wp.com/latex.php?latex=X&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='X' title='X' class='latex' /> is the <img src='http://s0.wp.com/latex.php?latex=N&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='N' title='N' class='latex' />:th member of <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' />, starting from <img src='http://s0.wp.com/latex.php?latex=0&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='0' title='0' class='latex' />. One observation is enough to give us a solution: <img src='http://s0.wp.com/latex.php?latex=X&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='X' title='X' class='latex' /> is the <img src='http://s0.wp.com/latex.php?latex=N&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='N' title='N' class='latex' />:th element of <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> if the number of elements preceding <img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> is equal to <img src='http://s0.wp.com/latex.php?latex=N&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='N' title='N' class='latex' />. This is easy to check with <img src='http://s0.wp.com/latex.php?latex=length%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='length/2' title='length/2' class='latex' />:</p>
<p><pre class="brush: plain;">
    nth(X, Xs, N) :-
        append(A, [X|_], Xs),
        length(A, N).
</pre></p>
<p>A question to the observant reader: why is the order of the two goals in the body not swapped? Also, as a concluding remark: I&#8217;ve been told that it&#8217;s not always a good idea to do something just because you can. That might well be true. This version of <img src='http://s0.wp.com/latex.php?latex=nth%2F3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='nth/3' title='nth/3' class='latex' /> is rather inefficient and I would not recommend anyone to try it at home!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/491/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=491&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/10/24/arcane-abuses-of-append/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>
	</item>
		<item>
		<title>Delightful Summer Reading</title>
		<link>http://prologomenon.wordpress.com/2011/07/16/delightful-summer-reading/</link>
		<comments>http://prologomenon.wordpress.com/2011/07/16/delightful-summer-reading/#comments</comments>
		<pubDate>Sat, 16 Jul 2011 16:58:39 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=482</guid>
		<description><![CDATA[Apologies for the lack of updates! In my defense, I&#8217;ve been rather busy in an attempt to finish the drafts of not only one, but two, novels. The first of these is about bananas, puns and slapstick humour while the second is heavily influenced by my interest in logic and incompleteness. Over the course of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=482&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Apologies for the lack of updates! In my defense, I&#8217;ve been rather busy in an attempt to finish the drafts of not only one, but two, novels. The first of these is about bananas, puns and slapstick humour while the second is heavily influenced by my interest in logic and incompleteness. Over the course of the summer I&#8217;ve also been doing a fair amount of reading. The two non-fiction books that I&#8217;m currently digging my teeth in are <em>The World of Mathematics</em> and <em>Logic, Logic and Logic</em>.</p>
<p><a href="http://prologomenon.files.wordpress.com/2011/07/books.jpg"><img class="alignnone size-full wp-image-485" title="books" src="http://prologomenon.files.wordpress.com/2011/07/books.jpg?w=519" alt=""   /></a></p>
<p>The World of Mathematics is a vast collection of essays (the Swedish edition, Sigma, consists of six volumes in total!) spanning topics such as biographies of the great thinkers, historical problems and also more recent investigations of the foundations of mathematics. Highly recommended, and as a bonus it looks great in the bookshelf.</p>
<p>Logic, Logic and Logic is a collection of articles by the prominent logician-philosopher George Boolos. The bulk of the text is dedicated to various papers on Frege, that among other things sheds light of the importance of his <em>Begriffsschrift</em>. You probably knew that Frege&#8217;s life work was demolished when Bertrand Russel presented his infamous paradox in a letter to him, but surprisingly enough it has been found that a rather large portion of it can be salvaged by very small means. The end result is a consistent, second order theory of arithmetics that in some ways is much more elegant than the usual Peano axiomatic formulation (these are instead derived). The fine details are not always that easy to follow, but Boolos&#8217; interesting philosophical remarks makes it worthwhile in the end. Also recommended!</p>
<p>If time permits, I&#8217;ll also revisit <em>Computing With Logic</em> by David Maier and David S. Warren. For some reason I left it half unfinished when I read it the last time. It more or less contains everything you need to know about the theory and practice to implement a reasonably efficient Prolog system (excluding parsing), and could potentially serve as inspiration for a few blog entries in a not-so-distant future.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/482/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=482&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/07/16/delightful-summer-reading/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>

		<media:content url="http://prologomenon.files.wordpress.com/2011/07/books.jpg" medium="image">
			<media:title type="html">books</media:title>
		</media:content>
	</item>
		<item>
		<title>Prolog&#8217;s Makin&#8217; Music &#8211; Part 3</title>
		<link>http://prologomenon.wordpress.com/2011/06/19/prologs-makin-music-part-3/</link>
		<comments>http://prologomenon.wordpress.com/2011/06/19/prologs-makin-music-part-3/#comments</comments>
		<pubDate>Sun, 19 Jun 2011 11:27:39 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Logic programming]]></category>
		<category><![CDATA[Logtalk]]></category>
		<category><![CDATA[Music]]></category>
		<category><![CDATA[Prolog]]></category>
		<category><![CDATA[Xenakis]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=429</guid>
		<description><![CDATA[This time we&#8217;ll have a look at some techniques for automatically generating music &#8212; or rather, to be more accurate, melodies. Since we&#8217;ve deduced that a musical scale is a mathematical structure in which it&#8217;s possible to perform all the standard operations, we have quite a lot of freedom when it comes to the choice [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=429&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This time we&#8217;ll have a look at some techniques for automatically generating music &#8212; or rather, to be more accurate, melodies. Since we&#8217;ve deduced that a musical scale is a mathematical structure in which it&#8217;s possible to perform all the standard operations, we have quite a lot of freedom when it comes to the choice of a suitable formalism. We&#8217;ll also make some simplifications to make the job easier: namely that our melodies consists of a single list of notes where all notes are assumed to be of equal importance, e.g. played in the same timbre and tempo. This means that the resulting melodies won&#8217;t be that pleasing to the ear, but there&#8217;s of course nothing that stops us from using one of these melodies as a building block in a larger musical composition. I suppose that we still need musicians for something!</p>
<h3>Lindenmayer systems</h3>
<p>A Lindermayer system, or an L-system, is a formal grammar quite similar to a context-free grammar. The goal is to rewrite a starting string, the axiom, by applying as many rules as possible. A rule is simply an if-then statement of the form: if the token is <img src='http://s0.wp.com/latex.php?latex=X&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='X' title='X' class='latex' /> then replace it by <img src='http://s0.wp.com/latex.php?latex=Y&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Y' title='Y' class='latex' />. Formally speaking this information can be summarized as a tuple:</p>
<p><img src='http://s0.wp.com/latex.php?latex=L+%3D+%28V%2C+%5Comega%2C+P%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='L = (V, &#92;omega, P)' title='L = (V, &#92;omega, P)' class='latex' /></p>
<p>Where <img src='http://s0.wp.com/latex.php?latex=V&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='V' title='V' class='latex' /> is a set of variables, <img src='http://s0.wp.com/latex.php?latex=%5Comega&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;omega' title='&#92;omega' class='latex' /> the starting axiom and <img src='http://s0.wp.com/latex.php?latex=P&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='P' title='P' class='latex' /> the set of production rules, i.e. functions from <img src='http://s0.wp.com/latex.php?latex=V&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='V' title='V' class='latex' /> to the language. The symbols that don&#8217;t appear in <img src='http://s0.wp.com/latex.php?latex=V&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='V' title='V' class='latex' />, the constants, are always left untouched. The first example on <a href="http://en.wikipedia.org/wiki/L-system">Wikipedia</a> is an Algae system. It has two variables, <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> as starting axiom and the two rules:</p>
<p><img src='http://s0.wp.com/latex.php?latex=A+%5Crightarrow+AB&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A &#92;rightarrow AB' title='A &#92;rightarrow AB' class='latex' /></p>
<p><img src='http://s0.wp.com/latex.php?latex=B+%5Crightarrow+A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B &#92;rightarrow A' title='B &#92;rightarrow A' class='latex' /></p>
<p>So the strings that will be produced are: <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=AB&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='AB' title='AB' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=ABA&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='ABA' title='ABA' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=ABAAB&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='ABAAB' title='ABAAB' class='latex' />, and so on. It shouldn&#8217;t be hard to see how the rules were applied. First the axiom was used. Then, the rule for <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> was used which produced <img src='http://s0.wp.com/latex.php?latex=AB&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='AB' title='AB' class='latex' />. Then the rules for both <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> were used which produced <img src='http://s0.wp.com/latex.php?latex=AB&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='AB' title='AB' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' />, i.e. <img src='http://s0.wp.com/latex.php?latex=ABA&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='ABA' title='ABA' class='latex' />.</p>
<p>We are free to interpret the structure in an L-system in any way we see fit. For example, we could interpret <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' /> in the Algae system as &#8220;play the first note in the scale&#8221; and <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' /> as &#8220;play the second note in the scale&#8221;. I shall however use something a bit closer to the Logo notation that is commonly used to visualize L-systems. It consists of the following commands:</p>
<ul>
<li><img src='http://s0.wp.com/latex.php?latex=f&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='f' title='f' class='latex' /> &#8212; draw forward.</li>
<li><img src='http://s0.wp.com/latex.php?latex=%2B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='+' title='+' class='latex' /> &#8212; turn right.</li>
<li><img src='http://s0.wp.com/latex.php?latex=-&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='-' title='-' class='latex' />  &#8212; turn left.</li>
<li><img src='http://s0.wp.com/latex.php?latex=s&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='s' title='s' class='latex' /> &#8212; push the current point on the stack.</li>
<li><img src='http://s0.wp.com/latex.php?latex=r&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='r' title='r' class='latex' /> &#8212; pop an entry from the stack.</li>
</ul>
<p>But since we&#8217;re working with scales, and not images, we have to reinterpret these commands. I propose the following:</p>
<div>
<ul>
<li><img src='http://s0.wp.com/latex.php?latex=f&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='f' title='f' class='latex' /> &#8212; play the current note.</li>
<li><img src='http://s0.wp.com/latex.php?latex=%2B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='+' title='+' class='latex' /> &#8212; increase the current note.</li>
<li><img src='http://s0.wp.com/latex.php?latex=-&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='-' title='-' class='latex' /> &#8212; decrease the current note.</li>
<li><img src='http://s0.wp.com/latex.php?latex=s&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='s' title='s' class='latex' /> &#8212; push the current note on the stack.</li>
<li><img src='http://s0.wp.com/latex.php?latex=r&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='r' title='r' class='latex' /> &#8212; pop an entry from the stack.</li>
</ul>
<p>Hence we&#8217;re going to use L-systems that produce strings in this format. From such a string it&#8217;s then possible to extract a melody. For example, the string <img src='http://s0.wp.com/latex.php?latex=%22f%2Bf-f%22&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&quot;f+f-f&quot;' title='&quot;f+f-f&quot;' class='latex' /> could be interpreted as the notes <img src='http://s0.wp.com/latex.php?latex=0%2C1%2C0&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='0,1,0' title='0,1,0' class='latex' />.</p>
</div>
<p>We&#8217;ll return to this later. For now, let&#8217;s concentrate on implementing L-systems in Logtalk. This can be done in a large number of ways, but once we&#8217;ve chosen a suitable representation everything else will more or less follow automatically. Every L-system will be represented by an axiom and a set of production rules for both variables and constants. Since the production rules take symbols as argument and produces strings/lists, DCG&#8217;s are a fine choice. For the moment we can ignore everything else and just stipulate what an L-system <em>is</em>.</p>
<p><pre class="brush: plain;">
:- protocol(l_system).

   :- public(rule//1).
   :- public(axiom/1).

:- end_protocol.

:- object(algae,
    implements(l_system)).

   axiom([a]).

   rule(a) --&gt; [a,b].
   rule(b) --&gt; [a].

:- end_object.
</pre></p>
<p>Then we&#8217;ll need a predicate that takes a string as input and applies all applicable production rules. Since the rules themselves are written in DCG notation, it&#8217;s easiest to continue with this trend. The predicate will take a string and an L-system as input, and iteratively apply the rules for the elements in the string.</p>
<p><pre class="brush: plain;">

next([], _) --&gt; [].
next([X|Xs], L) --&gt;
    L::rule(X),
    next(Xs, L).
</pre></p>
<p>And all that remains is a predicate that calls <img src='http://s0.wp.com/latex.php?latex=next%2F%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='next//2' title='next//2' class='latex' /> for a predetermined number of generations. It&#8217;s more or less a standard loop: if <img src='http://s0.wp.com/latex.php?latex=N&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='N' title='N' class='latex' /> is <img src='http://s0.wp.com/latex.php?latex=1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='1' title='1' class='latex' />, then the resulting string is the axiom of the L-system. Otherwise, recursively run the L-system for <img src='http://s0.wp.com/latex.php?latex=N+-+1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='N - 1' title='N - 1' class='latex' /> generations and then run it once more.</p>
<p><pre class="brush: plain;">
generation(1, L, X) :-
    L::axiom(X).
generation(N, L, X) :-
    N &gt; 1,
    N1 is N - 1,
    generation(N1, L, Y),
    phrase(next(Y, L), X, []).
</pre></p>
<p>This is almost <em>too </em>easy! For reference, let&#8217;s also implement an L-system that makes use of the Logo commands previously discussed.</p>
<p><pre class="brush: plain;">
:- object(koch_curve,
    implements(l_system)).

    axiom([f]).

    rule(-) --&gt; [-].
    rule(+) --&gt; [+].
    rule(f) --&gt; [f,+,f,-,f,-,f,+,f].
:- end_object.
</pre></p>
<p>This structure is known as a Koch curve, and when interpreted as drawing commands it looks like:</p>
<p><img class="alignnone" title="Koch curve" src="http://upload.wikimedia.org/wikipedia/commons/d/d6/Square_koch_3.svg" alt="" width="280" height="140" /></p>
<p>Now we&#8217;ll need a predicate that transforms a list of commands into a list of notes. It&#8217;ll need 4 input arguments:</p>
<ul>
<li><img src='http://s0.wp.com/latex.php?latex=Xs&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Xs' title='Xs' class='latex' /> &#8212; the list of commands.</li>
<li><img src='http://s0.wp.com/latex.php?latex=Scale&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Scale' title='Scale' class='latex' /> &#8212; the scale that the notes shall be generated according to.</li>
<li><img src='http://s0.wp.com/latex.php?latex=N&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='N' title='N' class='latex' /> &#8212; the starting/current note.</li>
<li><img src='http://s0.wp.com/latex.php?latex=S&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='S' title='S' class='latex' /> &#8212; the stack.</li>
</ul>
<p>And one single output argument:</p>
<ul>
<li><img src='http://s0.wp.com/latex.php?latex=Ns&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ns' title='Ns' class='latex' /> &#8212; the resulting list of notes.</li>
</ul>
<p>It&#8217;s not that hard to implement since it  only consists of a case-analysis of the command list. For example, if the command list is empty then the list of notes is empty. If the command is <img src='http://s0.wp.com/latex.php?latex=f&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='f' title='f' class='latex' />, then we add the current note <img src='http://s0.wp.com/latex.php?latex=N&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='N' title='N' class='latex' /> to <img src='http://s0.wp.com/latex.php?latex=Ns&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ns' title='Ns' class='latex' />, and so on for all the other commands.</p>
<p><pre class="brush: plain;">
    transform([], _, _, _, []).
    transform([f|Cs], Scale, N, S, [N|Ns]) :-
        transform(Cs, Scale, N, S, Ns).
    transform([-|Cs], Scale, N, S, Ns) :-
        Scale::lower(N, N1),
        transform(Cs, Scale, N1, S, Ns).
    transform([+|Cs], Scale, N, S, Ns) :-
        Scale::raise(N, N1),
        transform(Cs, Scale, N1, S, Ns).
    transform([s|Cs], Scale, N, S, Ns) :-
        transform(Cs, Scale, N, [N|S], Ns).
    transform([r|Cs], Scale, _, [N|S], Ns) :-
        transform(Cs, Scale, N, S, Ns).
</pre></p>
<h3>Putting everything together</h3>
<p>We can now generate command strings from L-systems and convert these into notes in a given scale. What remains is to convert the notes into frequencies with a specific duration. These can then be converted into samples and be written to a WAV file.</p>
<p><pre class="brush: plain;">
    generate_notes(L, I, Scale, Notes, Number_Of_Samples) :-
       l_systems::generation(I, L, X),
       Scale::nth(0, Tonic),
       l_systems::transform(X, Scale, Tonic, [], Notes0),
       findall(F-0.2,
              (list::member(Note, Notes0),
               Scale::frequency(Note, F)),
              Notes),
       length(Notes, Length),
       synthesizer::sample_rate(SR),
       Number_Of_Samples is Length*(SR/5).
</pre></p>
<p>The value <img src='http://s0.wp.com/latex.php?latex=0.2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='0.2' title='0.2' class='latex' />, the duration of each note, is of course just an example and can be changed at whim. This is all we need in order to crank out some simple tunes. Luckily, I&#8217;ve already prepared some samples for your auditory pleasure.</p>
<p><a href="http://soundcloud.com/prologomenon/koch-curve-in-c-major">Koch curve in C major</a></p>
<p>This is the curve depicted earlier. To be frank it sounds kind of dreadful, but fortunately the other samples are somewhat more interesting. Next up is the dragon curve!</p>
<p><img class="alignnone" title="Dragon curve" src="http://upload.wikimedia.org/wikipedia/commons/1/11/Dragon_curve_L-system.svg" alt="" width="288" height="187" /></p>
<p><a href="http://soundcloud.com/prologomenon/dragon-curve-in-c-major/">Dragon curve in C major</a></p>
<p><a href="http://soundcloud.com/prologomenon/dragon-curve-in-c-minor/">Dragon curve in C minor</a></p>
<p>I think it sounds much better than the Koch curve, but that might be due to the fact that I view my creations with rose-tinted eyes; unable to see the unholy abomination that is their true form. Let&#8217;s have a look at the Hilbert curve.</p>
<p><img class="alignnone" title="Hilbert curve" src="http://upload.wikimedia.org/wikipedia/commons/7/70/Hilbert-Kurve.png" alt="" width="267" height="263" /></p>
<p><a href="http://soundcloud.com/prologomenon/hilbert-curve-in-c-major">Hilbert curve in C major</a></p>
<p><a href="http://soundcloud.com/prologomenon/hilbert-curve-in-c-minor">Hilbert curve in C minor</a></p>
<p>Catchy! The last L-system is a fractal plant.</p>
<p><img class="alignnone" src="http://resumbrae.com/ub/dms423/24/Fractal_plant.jpg" alt="" width="232" height="234" /></p>
<p><a href="http://soundcloud.com/prologomenon/fractal-plant-in-c-major">Fractal plant in C major</a></p>
<p><a href="http://soundcloud.com/prologomenon/fractal-plant-in-c-minor">Fractal plant in C minor</a></p>
<p>I think the results are quite interesting, and this is only the tip of the iceberg since it&#8217;s possible to create any kind of L-system and interpret it as a melody. The whole set is available at <a href="http://soundcloud.com/prologomenon/sets/l-system-madness/">Soundcloud</a>.</p>
<p>I initially intended to include a section in which I created a Prolog interpreter that for each refutation also produced a melody, but the time is already running out. It&#8217;s not impossible that I&#8217;ll return to the subject at a later date however!</p>
<h3>Source code</h3>
<p>The source code is available at <a href="https://gist.github.com/1034067">https://gist.github.com/1034067</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/429/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=429&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/06/19/prologs-makin-music-part-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>

		<media:content url="http://upload.wikimedia.org/wikipedia/commons/d/d6/Square_koch_3.svg" medium="image">
			<media:title type="html">Koch curve</media:title>
		</media:content>

		<media:content url="http://upload.wikimedia.org/wikipedia/commons/1/11/Dragon_curve_L-system.svg" medium="image">
			<media:title type="html">Dragon curve</media:title>
		</media:content>

		<media:content url="http://upload.wikimedia.org/wikipedia/commons/7/70/Hilbert-Kurve.png" medium="image">
			<media:title type="html">Hilbert curve</media:title>
		</media:content>

		<media:content url="http://resumbrae.com/ub/dms423/24/Fractal_plant.jpg" medium="image" />
	</item>
		<item>
		<title>Prolog&#8217;s Makin&#8217; Music &#8211; Part 2</title>
		<link>http://prologomenon.wordpress.com/2011/06/04/prologs-makin-music-part-2/</link>
		<comments>http://prologomenon.wordpress.com/2011/06/04/prologs-makin-music-part-2/#comments</comments>
		<pubDate>Sat, 04 Jun 2011 11:49:00 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Logic programming]]></category>
		<category><![CDATA[Logtalk]]></category>
		<category><![CDATA[Music]]></category>
		<category><![CDATA[Prolog]]></category>
		<category><![CDATA[Xenakis]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=377</guid>
		<description><![CDATA[Scales, scales and scales It&#8217;s time to bring on the noise! To recapitulate the story thus far, it suffices to say that we&#8217;re now able to write raw audio data in the WAV format after some mysterious bit-fiddling. As already mentioned we could in principle start to crank out tunes in this stage, but to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=377&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Scales, scales and scales</h3>
<p>It&#8217;s time to bring on the noise! To recapitulate the story thus far, it suffices to say that we&#8217;re now able to write raw audio data in the WAV format after some mysterious bit-fiddling. As already mentioned we could in principle start to crank out tunes in this stage, but to illustrate why this isn&#8217;t a good idea I have prepared a small sample file containing 1 million randomly generated samples in the range <img src='http://s0.wp.com/latex.php?latex=%5B-32768%2C+32767%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[-32768, 32767]' title='[-32768, 32767]' class='latex' />. It is perhaps also instructive to see a visual representation of the samples. Here&#8217;s the results:</p>
<p><a href="http://prologomenon.files.wordpress.com/2011/06/random_samples.png"><img class="alignnone size-full wp-image-378" title="random_samples" src="http://prologomenon.files.wordpress.com/2011/06/random_samples.png?w=519" alt=""   /></a></p>
<p><a href="http://soundcloud.com/prologomenon/random-samples" target="_blank">Soundcloud link.</a><br />
As expected the result is garbled noise. There&#8217;s obviously no discernible structure to speak of since the samples are literally speaking all over the place. We want something more harmonic and symmetrical that we can actually work with. Why does classical instruments (excluding drums, cymbals and other unpitched instruments) have such nice acoustic properties? To make a long story short, many instruments produce sounds with the help of vibrating strings &#8211; oscillations at different frequencies, e.g. a sine wave. Different frequencies give us different tones. In e.g. a piano the keys to the right have higher frequencies than those to the left. Hence, to construct something akin to an instrument we need a system of  frequencies and a function that can generate the corresponding waves. Obviously these problems have already been solved many times over in the history of music theory, and it would be ignorant to not take advantage of this. Let&#8217;s start with the first problem of finding a system of frequencies, a <em>scale</em>. This is actually harder than expected. We know that the scale should go from lower to higher frequencies and that there at the very least should exist some relationship between them. A first attempt might be to start the scale at an arbitrary frequency, e.g. <img src='http://s0.wp.com/latex.php?latex=500&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='500' title='500' class='latex' />, and for every new frequency add <img src='http://s0.wp.com/latex.php?latex=50&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='50' title='50' class='latex' />. This would result in a scale where the difference between any two adjacent frequencies is constant, or in other words linear. With <img src='http://s0.wp.com/latex.php?latex=12&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='12' title='12' class='latex' /> frequencies we would obtain:</p>
<p>0 500<br />
1 550<br />
2 600<br />
3 650<br />
4 700<br />
5 750<br />
6 800<br />
7 850<br />
8 900<br />
9 950<br />
10 1000<br />
11 1050</p>
<p>Our first scale! The first number in the column, the identification number, is called a note (to be more precise a note also needs a duration). Hence the purpose of the scale is to give frequencies to notes. The traditional notation (pun not intended) for a series of <img src='http://s0.wp.com/latex.php?latex=12&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='12' title='12' class='latex' /> notes is <img src='http://s0.wp.com/latex.php?latex=A&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A' title='A' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=A%5Csharp&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='A&#92;sharp' title='A&#92;sharp' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=B&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='B' title='B' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=C&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='C' title='C' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=C%5Csharp&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='C&#92;sharp' title='C&#92;sharp' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='D' title='D' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=D%5Csharp&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='D&#92;sharp' title='D&#92;sharp' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=E&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='E' title='E' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=F&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='F' title='F' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=F%5Csharp&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='F&#92;sharp' title='F&#92;sharp' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=G&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G' title='G' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=G%5Csharp&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='G&#92;sharp' title='G&#92;sharp' class='latex' />, where the notes with funny looking sharp signs correspond to the small, black keys on a piano (so-called &#8220;accidentals&#8221;). For simplicity we&#8217;ll use the numeric notation though. The next question is how this scale sounds when it is played in succession.</p>
<p><a href="http://soundcloud.com/prologomenon/linear-scale-fr">Linear scale</a></p>
<p>Perhaps surprisingly, it sounds pretty terrible even though it&#8217;s not that simple to say why. Wrong starting frequency? Wrong increment? Well, maybe, but that&#8217;s not the real problem, namely that as the frequencies increase the perceived difference, the <em>distance</em>, gets smaller and smaller which results in an unsymmetrical scale. Hence we want a scale where the distance between any two adjacent frequencies is a constant. This is known as <em>equal temperament</em>. To be more precise the distance doesn&#8217;t have to be a constant, but it have to be a multiple of the smallest possible step in the scale. For example we could have a scale where the distance between the first and second frequency is <img src='http://s0.wp.com/latex.php?latex=1.5&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='1.5' title='1.5' class='latex' />, but where the distance between the second and third frequency is <img src='http://s0.wp.com/latex.php?latex=1.5+%5Ctimes+2+%3D+3&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='1.5 &#92;times 2 = 3' title='1.5 &#92;times 2 = 3' class='latex' />.</p>
<p>With this in mind it&#8217;s not to hard to create a new scale. The frequency of the <img src='http://s0.wp.com/latex.php?latex=N&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='N' title='N' class='latex' />:th note is then <img src='http://s0.wp.com/latex.php?latex=Start+%2A+Ratio%5E%7BN-1%7D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Start * Ratio^{N-1}' title='Start * Ratio^{N-1}' class='latex' />, where <img src='http://s0.wp.com/latex.php?latex=Start&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Start' title='Start' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=Ratio&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ratio' title='Ratio' class='latex' /> are constants. For <img src='http://s0.wp.com/latex.php?latex=Start+%3D+500&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Start = 500' title='Start = 500' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=Ratio+%3D+1.06978&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Ratio = 1.06978' title='Ratio = 1.06978' class='latex' /> we get the scale:</p>
<p>0 500.0<br />
1 534.89<br />
2 572.2<br />
3 612.1<br />
4 654.9<br />
5 700.6<br />
6 749.4<br />
7 801.7<br />
8 857.7<br />
9 917.5<br />
10 981.6<br />
11 1050.0</p>
<p><a href="http://soundcloud.com/prologomenon/equal-temperament-scale-from">Equal temperament scale</a></p>
<p>To be honest it still doesn&#8217;t sound very good, but at least it&#8217;s a step in the right direction. Somehow it doesn&#8217;t provide enough closure, and if we were to extend it even further the new notes wouldn&#8217;t really relate to the old notes in a natural way (what is &#8220;natural&#8221; is of course biased by experience and tradition). Here&#8217;s an idea: what if the extended frequencies were (approximately) multiples of the first <img src='http://s0.wp.com/latex.php?latex=12&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='12' title='12' class='latex' /> frequencies? That is <img src='http://s0.wp.com/latex.php?latex=F_%7B12%7D+%5Capprox+2+%5Ctimes+F_0&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='F_{12} &#92;approx 2 &#92;times F_0' title='F_{12} &#92;approx 2 &#92;times F_0' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=F_%7B13%7D+%5Capprox+2+%5Ctimes+N_1&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='F_{13} &#92;approx 2 &#92;times N_1' title='F_{13} &#92;approx 2 &#92;times N_1' class='latex' /> and so on. It&#8217;s not too hard to derive such a constant. Let <img src='http://s0.wp.com/latex.php?latex=x&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='x' title='x' class='latex' /> be the constant. Then <img src='http://s0.wp.com/latex.php?latex=F_%7B12%7D+%3D+2%5Ctimes+F_0+%3D+F_0+%5Ctimes+x+%5E%7B12%7D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='F_{12} = 2&#92;times F_0 = F_0 &#92;times x ^{12}' title='F_{12} = 2&#92;times F_0 = F_0 &#92;times x ^{12}' class='latex' /> <img src='http://s0.wp.com/latex.php?latex=%5CLeftrightarrow+%5Cfrac%7B2%5Ctimes+F_0%7D%7BF_0%7D+%3D+x%5E%7B12%7D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;Leftrightarrow &#92;frac{2&#92;times F_0}{F_0} = x^{12}' title='&#92;Leftrightarrow &#92;frac{2&#92;times F_0}{F_0} = x^{12}' class='latex' /> <img src='http://s0.wp.com/latex.php?latex=%5CRightarrow+2%5E%7B1%2F12%7D+%3D+x&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;Rightarrow 2^{1/12} = x' title='&#92;Rightarrow 2^{1/12} = x' class='latex' />. Hence the general formula is <img src='http://s0.wp.com/latex.php?latex=F_n+%3D+F_0+%5Ctimes+x%5E%7Bn%7D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='F_n = F_0 &#92;times x^{n}' title='F_n = F_0 &#92;times x^{n}' class='latex' /> <img src='http://s0.wp.com/latex.php?latex=%3D+F_0+%5Ctimes+%282%5E%7B1%2F12%7D%29%5En&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='= F_0 &#92;times (2^{1/12})^n' title='= F_0 &#92;times (2^{1/12})^n' class='latex' /> <img src='http://s0.wp.com/latex.php?latex=%3D+F_0+%5Ctimes+2%5E%7Bn%2F12%7D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='= F_0 &#92;times 2^{n/12}' title='= F_0 &#92;times 2^{n/12}' class='latex' />.</p>
<p>If the starting frequency is 500 we then get the scale:</p>
<p>0 500.0<br />
1 529.7<br />
2 561.2<br />
3 594.6<br />
4 629.0<br />
5 667.4<br />
6 707.1<br />
7 749.2<br />
8 793.7<br />
9 840.9<br />
10 890.9<br />
11 943.9</p>
<p><a href="http://soundcloud.com/prologomenon/equal-temperament-scale-from-1">Equal temperament scale &#8211; second attempt</a></p>
<p>It&#8217;s hard to notice the difference in the first few notes, but in the end of the scale the difference gets more and more pronounced. Now we have something quite close to what&#8217;s actually used in the real world. The only difference is the starting frequency, which is usually 440 Hz, the so-called standard concert pitch. This value is somewhat arbitrary, but just for reference here&#8217;s what we get:</p>
<p>0 440.0<br />
1 466.2<br />
2 493.9<br />
3 523.3<br />
4 554.4<br />
5 587.3<br />
6 622.3<br />
7 659.3<br />
8 698.5<br />
9 739.9<br />
10 783.9<br />
11 830.6</p>
<p><a href="http://soundcloud.com/prologomenon/the-chromatic-scale-from-440">Chromatic scale</a></p>
<p>Fortunately it&#8217;s rather easy to implement scales once we have the theory behind us. There are two basic choices for the representation: either  we work with the raw frequencies in the scale, or we work with the notes and extract the frequencies when needed. I shall go with the second option since it&#8217;s often easier to work with notes. Interestingly enough, the chromatic 12 tone scale that we just used is an example of an abelian (commutative) group with <img src='http://s0.wp.com/latex.php?latex=0&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='0' title='0' class='latex' /> as the unit element, which means that it&#8217;s quite pleasant to work with. The basic operations that we want to perform are:</p>
<ul>
<li>raise/2 &#8211; get the next note in the scale.</li>
<li>lower/2 &#8211; get the preceding note in the scale.</li>
<li>add/3 &#8211; add two notes in the scale.</li>
<li>length/1 &#8211; get the number of notes in the scale.</li>
<li>nth/2 &#8211; get the n:th note in the scale, starting from 0.</li>
<li>frequency/2 &#8211; get the associated frequency of the note.</li>
</ul>
<p>Which is easily expressible in terms of a protocol:</p>
<p><pre class="brush: plain;">
:- protocol(scalep).

   :- public(raise/2).
   :- public(lower/2).
   :- public(add/3).
   :- public(nth/2).
   :- public(length/1).
   :- public(frequency/2).

:- end_protocol.
</pre></p>
<p>And to implement the chromatic scale is straightforward:</p>
<p><pre class="brush: plain;">
:- object(chromatic_scale,
        implements(scalep)).

    %A, A#, ..., G, G#.
    length(12).

    raise(N, N1) :-
        N1 is (N + 1) mod 12.

    lower(N, N1) :-
        N1 is (N - 1) mod 12.

    add(N1, N2, N3) :-
        N3 is (N1 + N2) mod 12.

    nth(I, I) :-
        % Used so that we can call nth/2 with uninstantiated
        % arguments.
        between(1, 12, I).

    %A4 to G#5.
    frequency(N, F) :-
        F is 440 * 2 ** (N/12).

:- end_object.
</pre></p>
<p>Extending this scale to use more than 12 elements would of course not be hard either. Just to show something different we&#8217;re also going to implement the C major scale. It contains the frequencies:</p>
<p>0 523.3<br />
1 587.3<br />
2 659.3<br />
3 698.5<br />
4 783.9<br />
5 880<br />
6 987.8</p>
<p><a href="http://soundcloud.com/prologomenon/the-c-major-scale-from-523-hz">The C major scale</a></p>
<p>It&#8217;s slightly harder to implement than the chromatic scale since the distances between adjacent notes is not constant. The distance between any two adjacent notes is either a half step (the distance between two adjacent notes in the chromatic scale) or two half steps. If we then represent each note with its distance from the first note we get:</p>
<p>0 0<br />
1 2<br />
2 4<br />
3 5<br />
4 7<br />
5 9<br />
6 11</p>
<p>Don&#8217;t worry if these specific distances doesn&#8217;t make any sense to you. But they are not completely arbitrary; each note in C major corresponds to a white key on the piano, and is actually the only major scale that only makes use the white keys. Since we are now counting half-steps we can more or less use the same formula as in the chromatic scale for calculating frequencies.</p>
<p><pre class="brush: plain;">
:- object(c_major,
        implements(scalep)).

    nth(0, 0).
    nth(1, 2).
    nth(2, 4).
    nth(3, 5).
    nth(4, 7).
    nth(5, 9).
    nth(6, 11).

    raise(N, N1) :-
        nth(I1, N),
        I2 is ((I1 + 1) mod 7),
        nth(I2, N1).

    lower(N, N1) :-
        nth(I1, N),
        I2 is ((I1 - 1) mod 7),
        nth(I2, N1).

    % As far as I know, this is the only way to make sense of addition
    % in C major. Simply adding the distance from the tonic doesn't work
    % since that makes it possible to get notes outside the scale.
    add(N1, N2, N3) :-
        nth(I1, N1),
        nth(I2, N2)
        I3 is ((I1 + I2) mod 7),
        nth(I3, N3).

    % C, D, E, F, G, A, B.
    length(7).

    %C5 to B5.
    frequency(N, F) :-
        F is 440 * 2 ** ((N + 3)/12).

:- end_object.
</pre></p>
<h3>The synthesizer</h3>
<p>Whenever we&#8217;re going to generate music we&#8217;re going to use a specific scale in order to get a linear sequence of notes (since we don&#8217;t use chords). From the notes we get a series of frequencies. But to actually produce something that is nice to listen to we need something more. To play e.g. the standard concert pitch at 440 Hz we&#8217;re going to generate a wave with 440 oscillations per second. How we generate this wave determines how the note will be played. A sine wave will give a smooth sound while a sawtooth wave will give something reminiscent of a mechanical dentist drill. To create more complex sounds a technique known as <a href="http://en.wikipedia.org/wiki/Additive_synthesis">additive synthesis</a> can be used. We shall however not peruse this option at the moment.</p>
<p>Our synthesizer will take 3 input arguments: the frequency, the duration and the filter that shall be applied, and returns a list of samples in its single output argument. From the duration it&#8217;s possible to calculate how many samples that we&#8217;ll need to generate with the help of the sample rate. For example, if the duration is <img src='http://s0.wp.com/latex.php?latex=0.5&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='0.5' title='0.5' class='latex' /> seconds and the sample rate is <img src='http://s0.wp.com/latex.php?latex=22050&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='22050' title='22050' class='latex' /> the number of samples is <img src='http://s0.wp.com/latex.php?latex=0.5+%5Ctimes+22050&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='0.5 &#92;times 22050' title='0.5 &#92;times 22050' class='latex' /> <img src='http://s0.wp.com/latex.php?latex=%3D+11025&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='= 11025' title='= 11025' class='latex' />. The wave will be generated with a loop from <img src='http://s0.wp.com/latex.php?latex=0&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='0' title='0' class='latex' /> to <img src='http://s0.wp.com/latex.php?latex=Number%5C_Of%5C_Samples&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Number&#92;_Of&#92;_Samples' title='Number&#92;_Of&#92;_Samples' class='latex' /> where the following operations are performed on each sample:</p>
<ul>
<li>Divide the sample by the sample rate, so that we get the correct resolution. A high sample rate means that we&#8217;ll generate more points on the wave.</li>
<li>Calculate the angular frequency of the sample, i.e. <img src='http://s0.wp.com/latex.php?latex=%5Comega+%3D+2%5Cpi+F&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='&#92;omega = 2&#92;pi F' title='&#92;omega = 2&#92;pi F' class='latex' />, where <img src='http://s0.wp.com/latex.php?latex=F&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='F' title='F' class='latex' /> is the frequency.</li>
<li>Apply the filter. The filter should return a floating point number in <img src='http://s0.wp.com/latex.php?latex=%5B-1%2C+1%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[-1, 1]' title='[-1, 1]' class='latex' />.</li>
<li>Scale the sample in <img src='http://s0.wp.com/latex.php?latex=%5B-1%2C+1%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[-1, 1]' title='[-1, 1]' class='latex' /> with a volume factor so that we get samples in the full sample space.</li>
</ul>
<div>This can actually be done in rather few lines of code. Without further ado I present to you:</div>
<p><pre class="brush: plain;">
:- object(synthesizer).

    :- public(samples/4).
    :- public(sample_rate/1).
    :- public(bits_per_sample/1).

    :- private(filter/3).
    :- private(volume/3).
    :- private(wave//3).

    bits_per_sample(16).
    sample_rate(22050).

    samples(Frequency, Duration, Filter, Samples) :-
        sample_rate(SR),
        N is floor(SR * Duration),
        phrase(wave(N, Frequency, Filter), Samples).

    %% We could have implemented this as higher order predicates
    %% instead, but the performance loss would not have been worth it
    %% since the filter might be applied to millions of samples.
    filter(sine, Sample0, Sample) :-
        Sample is sin(Sample0).
    filter(sawtooth, Sample0, Sample) :-
        Sample is Sample0 - floor(Sample0).
    filter(triangle, Sample0, Sample) :-
        Sample is -((acos(sin(Sample0)) / pi - 0.5)*2).

    volume(M, N, V) :-
        bits_per_sample(BPS),
        V0 is (2**BPS)/2 - 1,
        %% Decrease the volume over time.
        Percent is (M/N)/2,
        V is V0*(1 - Percent).

    wave(N, Freq, F) --&gt; wave(0, N, Freq, F).
    wave(M, N, _, _) --&gt; {M &gt; N}, [].
    wave(M, N, Freq, F) --&gt;
        {M =&lt; N,
        sample_rate(SR),
        M1 is M + 1,
        volume(M, N, V),
        X is (2*pi*Freq)*M/SR,
        filter(F, X, Sample0),
        Sample is floor(Sample0*V)},
        [word(2, little, Sample)],
        wave(M1, N, Freq, F).

:- end_object.
</pre></p>
<h3>Putting everything together</h3>
<p>Somehow we&#8217;ve come this far without a suitable name for the project. I&#8217;ll name it <em>Xenakis</em> in honor of the Greek-French music theorist, composer and architect <a href="http://en.wikipedia.org/wiki/Iannis_Xenakis">Iannis Xenakis</a>. You can listen to one of his most famous pieces <a href="http://www.youtube.com/watch?v=SZazYFchLRI">here</a> (warning: it&#8217;s rather frightening).</p>
<p>Using the components just described is not hard. First one generates a list of frequencies in a scale, that is then used as input to the synthesizer which gives a list of samples which is written to a WAV file.</p>
<p><pre class="brush: plain;">
:- object(xenakis).

   :- public(init/0).

   init :-
       %% N is the number of samples.
       generate_notes(Ts, N),
       wav::prepare(output, N),
       write_samples(Ts).

   %% Generate the frequencies in the C major scale. Each note has a
   %% duration of 0.5 seconds.
   generate_notes(Ts, N) :-
       Scale = c_major,
       findall(F-0.5,
               (Scale::nth(_, Note),
                Scale::frequency(Note, F)),
               Ts),
       Scale::length(L),
       synthesizer::sample_rate(SR),
       N is L*SR/2.

   %% Write the notes to 'output'.
   write_samples([]).
   write_samples([F-D|Fs]) :-
        synthesizer::samples(F, D, sine, Samples),
        wav::write_audio(output, Samples),
        write_samples(Fs).

:- end_object.
</pre></p>
<p>All the scales that are available on Soundcloud were of course generated using this method. We now have a good foundation for the next installment where we at last will look at methods for automatically generating note sequences.</p>
<h3>Source code</h3>
<p>The source code is available at <a href="https://gist.github.com/1007820">https://gist.github.com/1007820</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/377/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/377/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/377/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/377/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/377/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/377/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/377/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/377/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/377/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/377/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/377/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/377/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/377/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/377/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=377&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/06/04/prologs-makin-music-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>

		<media:content url="http://prologomenon.files.wordpress.com/2011/06/random_samples.png" medium="image">
			<media:title type="html">random_samples</media:title>
		</media:content>
	</item>
		<item>
		<title>Prologomenon Tackles Logical Empiricism</title>
		<link>http://prologomenon.wordpress.com/2011/05/31/prologomenon-tackles-logical-empiricism/</link>
		<comments>http://prologomenon.wordpress.com/2011/05/31/prologomenon-tackles-logical-empiricism/#comments</comments>
		<pubDate>Tue, 31 May 2011 07:59:57 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Logic]]></category>
		<category><![CDATA[Ramblings]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=365</guid>
		<description><![CDATA[Back, at last! This time we&#8217;ll have a look on a movement close to our hearts: logical empiricism. The subject is not really related to logic programming at all, but I did this text as an assignment in a Philosophy of Science course and figured that I might as well post it here in the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=365&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Back, at last! This time we&#8217;ll have a look on a movement close to our hearts: logical empiricism. The subject is not really related to logic programming at all, but I did this text as an assignment in a Philosophy of Science course and figured that I might as well post it here in the case that someone finds it enjoyable.</p>
<p>Disclaimer one: It&#8217;s not particularly well-written and is probably full of errors and misunderstandings.<br />
Disclaimer two: I did an automatic LaTeX to HTML conversion that apparently couldn&#8217;t handle footnotes and references. Since I&#8217;m a lazy and unmoral person I simply left them as is.</p>
<p><strong>1. Introduction </strong></p>
<p>Science is concerned with theories that make claims about the physical world. Hence it should not come as a great surprise that there exists a relation between <em>facts</em> and <em>laws</em>. Can universal laws be logically derived from observational facts? The explication of this relation is not a problem of science, but rather a philosophical one that has plagued philosophers for centuries, and is surprisingly difficult to answer without retorting to circular or ad hoc arguments. This text will give a brief introduction to two important movements in the history of the philosophy of science: empiricism\footnote{Empiricism is sometimes grouped together with positivism and inductivism.} and logical empiricism. The focus will be on one of the most important principles in the logicism movement: the distinction between analytic and synthetic sentences.</p>
<p><strong>2. Empiricism </strong></p>
<p>Empiricism takes a radical stance in the question of how science is related to facts, and asserts the importance and infallibility of sensory experience and observation. The ideal view is that the human mind is a blank tablet, a <em>tabula rasa</em>, and that knowledge can only be gained from experience. Hence, a scientist should primarily conduct research by observing the world and derive general conclusions from the observations. This methodology is called <em>induction</em>. \footnote{Not to be confused with the concept of mathematical induction.} The logical form is:</p>
<p><img src='http://s0.wp.com/latex.php?latex=%7Bproperty%28a_0%29+%5Cwedge+property%28a_1%29+%5Cwedge+...+%5Cwedge+property%28a_n%29+%5CRightarrow+%5Cforall+x%3A%5C%2C+property%28x%29%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{property(a_0) &#92;wedge property(a_1) &#92;wedge ... &#92;wedge property(a_n) &#92;Rightarrow &#92;forall x:&#92;, property(x)}' title='{property(a_0) &#92;wedge property(a_1) &#92;wedge ... &#92;wedge property(a_n) &#92;Rightarrow &#92;forall x:&#92;, property(x)}' class='latex' /></p>
<p>Where we assume that <img src='http://s0.wp.com/latex.php?latex=%7Bx%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{x}' title='{x}' class='latex' /> is restricted to a suitable domain. Let us say that we are interested in the question of whether all copper conducts electricity, and have successfully verified this property in <img src='http://s0.wp.com/latex.php?latex=%7Bn%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{n}' title='{n}' class='latex' /> experiments. An application of the induction principle would then have the form:</p>
<p><img src='http://s0.wp.com/latex.php?latex=%7Bconducts%5C_electricity%28copper%5C_sample_1%29%5C%2C+%5Cwedge+%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{conducts&#92;_electricity(copper&#92;_sample_1)&#92;, &#92;wedge }' title='{conducts&#92;_electricity(copper&#92;_sample_1)&#92;, &#92;wedge }' class='latex' /></p>
<p><img src='http://s0.wp.com/latex.php?latex=%7Bconducts%5C_electricity%28copper%5C_sample_2%29%5C%2C+%5Cwedge+%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{conducts&#92;_electricity(copper&#92;_sample_2)&#92;, &#92;wedge }' title='{conducts&#92;_electricity(copper&#92;_sample_2)&#92;, &#92;wedge }' class='latex' /></p>
<p><img src='http://s0.wp.com/latex.php?latex=%7B.%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{.}' title='{.}' class='latex' /></p>
<p><img src='http://s0.wp.com/latex.php?latex=%7B.%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{.}' title='{.}' class='latex' /></p>
<p><img src='http://s0.wp.com/latex.php?latex=%7B.%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{.}' title='{.}' class='latex' /></p>
<p><img src='http://s0.wp.com/latex.php?latex=%7B%5Cwedge+%5C%2C+conducts%5C_electricity%28copper%5C_sample_n%29%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{&#92;wedge &#92;, conducts&#92;_electricity(copper&#92;_sample_n)}' title='{&#92;wedge &#92;, conducts&#92;_electricity(copper&#92;_sample_n)}' class='latex' /></p>
<p><img src='http://s0.wp.com/latex.php?latex=%7B%5CRightarrow+%5Cforall+x+%5Cin+Copper%3A%5C%2C+conducts%5C_electricity%28x%29%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{&#92;Rightarrow &#92;forall x &#92;in Copper:&#92;, conducts&#92;_electricity(x)}' title='{&#92;Rightarrow &#92;forall x &#92;in Copper:&#92;, conducts&#92;_electricity(x)}' class='latex' /></p>
<p>Both the premises and the conclusion are true, yet the reasoning is not logically valid. Any finite number of affirmative observations cannot prove the necessity of the general hypothesis. This is known as the <em>problem of induction</em> and was elucidated by David Hume in the eighteenth century. At first it might appear to be a pedantic and irrelevant objection since scientists rarely claim to work with absolute knowledge. If the induction principle allows us to derive more and more probable hypotheses then that should be good enough. Here is the catch: for any set of observed facts there exists an infinite number of incongruent hypotheses. Hence we cannot claim that our particular hypothesis is probable in the usual mathematical sense of the word. This should of course not be taken as an indication that inductive testing is void of meaning, but rather that it is inherently difficult to assign a truth value to a scientific theory (that has not been falsified).</p>
<p>This is not the only objection to empiricism. Among other things it can be argued that too much weight is placed on sensory experience, which can hardly be considered to be realistic since almost all observations are dependent on an underlying theory. Furthermore, why should one demand that theories have to be derived by induction when the principle is not logically valid?</p>
<p>Further critique can be found in e.g. Chalmers \cite{Chalmers}.</p>
<p><strong>3. Logical Empiricism </strong></p>
<p>Logic made great strides in the late eighteenth century and the beginning of the nineteenth century. The German mathematician and philosopher Gottlob Frege developed the first formal system capable of higher order logic in the outstanding, but also rather impervious, Begriffsschrift \cite{Frege}. Frege&#8217;s aim was to show that mathematics, starting with number theory, did not depend on empirical experience but was true a priory and could be inferred from pure logic alone. That is, it is <em>analytic</em> instead of <em>synthetic</em>. The sentence <em>There exists an infinite number of primes</em> is to Frege an analytic proposition that is true only in virtue of its constituents. At the same time the sentence <em>It will rain tomorrow</em> is synthetic since there is no logical reason why it has to be true or false &#8212; it can be confirmed or falsified by observations.</p>
<p>We have learned that pure, strict empiricism fell short for a number of reasons. Does this mean that there is no difference between science and e.g. religion? Intuitively one would like to claim that the most important difference is that the domains of discourse are different. In the first case claims are made about the physical world. In the second case the claims are, at least partly, metaphysical in nature. If one adheres to this demarcation principle then it is clear that it is pivotal to filter out statements that are metaphysical in a scientific theory. This was one of the aims set forth by Alfred Jules Ayer in Language, Truth and Logic \cite{Ayer}, which later became the epitome of logical empiricism \cite{Stanford}. With the advances made in formal logic, it was believed that it would be possible to define a verification principle for metaphysical propositions. Just like Frege, Ayer made a distinction between analytic and synthetic propositions. For a verification principle to be successful, then, it needs to be capable of ascertaining whether a synthetic proposition is empirical. Any sentence that failed the verification principle would be labeled as metaphysical and was asserted to be absolutely void of any meaningful content. This is a harsh claim, and it is perhaps not too surprising that the definition of a verification principle is irksome and prone to errors. Ayer gave the following criterion \cite{Stanford}:</p>
<p>A (synthetic) sentence <img src='http://s0.wp.com/latex.php?latex=%7BA%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{A}' title='{A}' class='latex' /> has empiric content if either:</p>
<ul>
<li><img src='http://s0.wp.com/latex.php?latex=%7BA+%5CRightarrow+O%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{A &#92;Rightarrow O}' title='{A &#92;Rightarrow O}' class='latex' />, where <img src='http://s0.wp.com/latex.php?latex=%7BO%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{O}' title='{O}' class='latex' /> is an observational sentence.</li>
<li>There exists a <img src='http://s0.wp.com/latex.php?latex=%7BB%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{B}' title='{B}' class='latex' /> such that <img src='http://s0.wp.com/latex.php?latex=%7BA+%5Cwedge+B+%5CRightarrow+O%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{A &#92;wedge B &#92;Rightarrow O}' title='{A &#92;wedge B &#92;Rightarrow O}' class='latex' />, where <img src='http://s0.wp.com/latex.php?latex=%7BO%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{O}' title='{O}' class='latex' /> is an observational sentence such that <img src='http://s0.wp.com/latex.php?latex=%7BB+%5CnRightarrow+O%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{B &#92;nRightarrow O}' title='{B &#92;nRightarrow O}' class='latex' />.</li>
</ul>
<p>The second criterion means that <img src='http://s0.wp.com/latex.php?latex=%7BA%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{A}' title='{A}' class='latex' /> can be used with another sentence, <img src='http://s0.wp.com/latex.php?latex=%7BB%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{B}' title='{B}' class='latex' />, to derive an observational sentence that could not have been derived from <img src='http://s0.wp.com/latex.php?latex=%7BB%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{B}' title='{B}' class='latex' /> alone.</p>
<p>It can be argued that this principle is at least necessary, but is it sufficient? Not at all. Consider any sentence <img src='http://s0.wp.com/latex.php?latex=%7BA%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{A}' title='{A}' class='latex' /> and an observational sentence <img src='http://s0.wp.com/latex.php?latex=%7BO%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{O}' title='{O}' class='latex' />. If it is possible to find a sentence <img src='http://s0.wp.com/latex.php?latex=%7BB%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{B}' title='{B}' class='latex' /> such that <img src='http://s0.wp.com/latex.php?latex=%7BA+%5Cwedge+B%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{A &#92;wedge B}' title='{A &#92;wedge B}' class='latex' /> necessarily implies <img src='http://s0.wp.com/latex.php?latex=%7BO%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{O}' title='{O}' class='latex' />, the principle fails. This is simple: take <img src='http://s0.wp.com/latex.php?latex=%7BB+%3D+A+%5CRightarrow+O%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{B = A &#92;Rightarrow O}' title='{B = A &#92;Rightarrow O}' class='latex' />. Then it can be shown by an application of modus ponens that <img src='http://s0.wp.com/latex.php?latex=%7BA+%5Cwedge+B+%5CRightarrow+O%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{A &#92;wedge B &#92;Rightarrow O}' title='{A &#92;wedge B &#92;Rightarrow O}' class='latex' />.</p>
<p>Even though this simplistic attempt failed, it is not impossible that a more complicated version could do the trick. Of course, this hinges on the fact that there is a distinction between synthetic and analytic propositions. If it can be argued that no such distinction can be made, then we would simply have to abandon the idea behind Ayer&#8217;s verification principle. This was the approach taken by Willard Van Orman Quine in his seminal paper <em>Two Dogmas of Empiricism</em> \cite{Quine} \footnote{Where the second &#8220;dogma&#8221; is reductionism}. Quine argues that the current notion of analyticity is circular in the sense that it relies on another concept, synonymy, that cannot be explained without referring to analyticity. The argument is best illustrated with examples. One of the hallmark sentences in the analytic tradition is <em>No unmarried man is married</em>, which is true no matter what &#8220;man&#8221; and &#8220;married&#8221; refers to if we agree that the logical syntax remains fixed. Quine then puts forth a second category of analytic sentences that can be transformed into logically true &#8212; analytic &#8212; sentences by replacing synonyms with synonyms. For example: <em>No bachelor is married.</em> We have to agree that this sentence is not logically true, at least not in the same sense as the preceding sentence, but could be taken as analytic once <em>bachelor</em> is replaced with <em>unmarried man</em>.</p>
<p>But when are two words synonyms? A dictionary is of no help here since it only records what is already known; there is no explanation behind the stated facts. The reasoning that two words are synonyms if they are interchangeable in all contexts fares no better, since this does not apply to e.g. &#8220;bachelor&#8221; and &#8220;unmarried man&#8221; if one puts them in the context &#8220;&#8230; has fewer than 10 words&#8221;. Let us however for the sake of the argument ignore syntactic differences between words. Is this kind of interchangeability good enough to describe synonymy?</p>
<p>Assume that &#8220;bachelor&#8221; and &#8220;unmarried man&#8221; are interchangeable in the sense just described. Then by the statement <em>Necessarily all and only bachelors are bachelors</em> we can conclude that <em>Necessarily all and only bachelors are unmarried men</em> by substituting &#8220;bachelor&#8221; for &#8220;unmarried man&#8221;. But to claim this last statement is to claim that the statement <em>All and only bachelors are unmarried men</em> is analytic! Why? Because if a statement is necessarily true then it is analytic, and we are back where we started since we need the concept of analyticity to explain the concept of synonymy.</p>
<p>If one agrees with Quine&#8217;s reasoning then no sharp distinction can be made between synthetic and analytic propositions, which would leave most of the original logicism program in shambles.</p>
<p><strong>4. Discussion </strong></p>
<p>As far as I can tell there is obviously no logical flaw in Quine&#8217;s argument. I am however a bit skeptic to the fact that he is so quick to dismiss synonyms as definitions. Does it really matter <em>why</em> two words are synonyms? I see no inherent problem in simply accepting the fact that some words have evolved to mean the same thing. This would however have the consequence that it is impossible to say that a sentence is analytic without assuming a specific, underlying theory. But is this a problem? Most mathematicians would argue that the sentence <img src='http://s0.wp.com/latex.php?latex=%7B1+%2B+1+%3D+2%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{1 + 1 = 2}' title='{1 + 1 = 2}' class='latex' /> is analytic, but this is only true if we assume the usual definition of <img src='http://s0.wp.com/latex.php?latex=%7B1%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{1}' title='{1}' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=%7B%2B%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{+}' title='{+}' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=%7B%3D%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{=}' title='{=}' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=%7B2%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{2}' title='{2}' class='latex' />; and would not be true if we interpreted <img src='http://s0.wp.com/latex.php?latex=%7B%2B%7D&amp;bg=efefef&amp;fg=000000&amp;s=0' alt='{+}' title='{+}' class='latex' /> as another relation. A better example can be found in geometry: is the parallel postulate analytic? Yes, if we are working in Euclidian geometry. No, if we are working in a non-Euclidean geometry.</p>
<p>Hence I still think that we can make a distinction between synthetic and analytic propositions, but only with respect to an underlying theory; though I would suspect that this notion of analyticity is not strong enough to be of any use in the logicism program.</p>
<p><strong><br />
References<br />
</strong></p>
<p>\bibitem{Chalmers} Alan Chalmers <em>What Is This Thing Called Science</em>. Hackett Pub Co, 1999.</p>
<p>\bibitem{Frege} Michael Potter and Tom Ricketts <em>The Cambridge Companion to Frege</em>. Cambridge University Press, 2010.</p>
<p>\bibitem{Ayer} Alfred Jules Ayer <em>Language, Truth and Logic</em>. Dover Publications; 2nd edition, 1952.</p>
<p>\bibitem{Stanford} Richard Creath <em>Logical Empiricism</em>. The Stanford Encyclopedia of Philosophy, Summer 2011 Edition.</p>
<p>\bibitem{Quine} Willard Van Orman Quine <em>Two Dogmas of Empiricism</em>. From a Logical Point of View, 1961.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/365/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=365&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/05/31/prologomenon-tackles-logical-empiricism/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>
	</item>
		<item>
		<title>Mullets, Moustaches and MicroPROLOG</title>
		<link>http://prologomenon.wordpress.com/2011/05/13/mullets-moustaches-and-microprolog/</link>
		<comments>http://prologomenon.wordpress.com/2011/05/13/mullets-moustaches-and-microprolog/#comments</comments>
		<pubDate>Fri, 13 May 2011 16:00:35 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Logic programming]]></category>
		<category><![CDATA[Prolog]]></category>
		<category><![CDATA[Ramblings]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=346</guid>
		<description><![CDATA[There was more to the eighties than funny looking moustaches, mullets and screaming electrical guitars. I&#8217;m of course talking about the home computer revolution: the era when the end-user was more or less expected to have a solid understand of how the hardware and software worked. Some time ago I thought it would be a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=346&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There was more to the eighties than funny looking moustaches, mullets and screaming electrical guitars. I&#8217;m of course talking about the home computer revolution: the era when the end-user was more or less expected to have a solid understand of how the hardware and software worked. Some time ago I thought it would be a great idea to deepen my knowledge of this period, and did what any self-respecting man or woman would do in my situation: grow a moustache &#8211; ehr, I mean: read a book about it. The book in question is named <em>The Personal Computer Handbook</em> (Swedish: Allt du behöver veta om persondatorer), and is precisely the kind of book that I would normally scoff at. If it was written today that assessment would probably be correct, but it managed to surpass my wildest imaginations. Just look at this image from the second page, and you&#8217;ll probably understand why:</p>
<p><a href="http://prologomenon.files.wordpress.com/2011/05/p4240082_small.jpg"><img class="alignnone size-medium wp-image-341" title="OLYMPUS DIGITAL CAMERA" src="http://prologomenon.files.wordpress.com/2011/05/p4240082_small.jpg?w=300&#038;h=289" alt="" width="300" height="289" /></a></p>
<p>That&#8217;s the future right there! And the book keeps delivering. Instead of explaining how one uses a word processor it delves deep in technical details about electronics, peripherals, computer architectures, micro code, assembly code and finally high-level languages such as BASIC, LOGO, COBOL, LISP and finally the Prolog dialect microPROLOG. The text goes as follows (disclaimer: this is my translation from the Swedish book. The English version probably differs!):</p>
<p><em>At Imperial College in London, a team under the direction of Robert Kowalski has worked on a simplified version of PROLOG (called microPROLOG) intended to foster the children&#8217;s capability in logical thinking. This capability is not restricted to computers, but can also be applied in other areas such as mathematics, French, history and geographics.    </em></p>
<p><em>While LOGO&#8217;s Turtle Graphics is based on the computer&#8217;s ability to create images and figures, microPROLOG is focused on the computer&#8217;s ability to manipulate symbolic expressions. But Turtle Graphics has proved to be a such successful system, that it has been included in some versions of microPROLOG.</em></p>
<p><em>Simple PROLOG programs can be built from propositions that contains names of individuals and relations between them.</em></p>
<p><em>One first constructs atomic propositions (so-called because they are the simplest possible propositions.) For example: Anders is-neighbor-with Lisa. Lotta is-friend-with Nicke. Lisa is-fighting-with Anders.</em></p>
<p><em>One can also construct molecular (composite) propositions, for example: Maria likes Johan if Johan likes Maria and Johan is-nice-to Maria. Or: x is-larger-than y if x is-larger-than z and z is-larger-than y. One can ask questions to the computer that are based on these facts and relations. Writing microPROLOG programs is like writing simplified and logically clear English, and the children becomes excited by the fact that the computer understands a language so close to their own.</em></p>
<p><em>MicroPROLOG is just like BASIC an interactive language, where the pupil can add, remove and modify the program and immediately see the result of the modification. Individuals in simple programs can be replaced by variables or lists, for example: Johan has-favourite-groups (Police, Roxy Music, ABBA).</em></p>
<p><em>PROLOG can handle such lists by first dividing them into a head and a tail. The head is the first element in the list, and the tail is the rest. The head in Johan&#8217;s list is therefore &#8220;Police&#8221;, and the tail is everything else in the parenthesis. The same head-tail structure is also found in LISP and LOGO.</em></p>
<p><em>Recent studies show that education in BASIC programming learn children how they should use the computers of the seventies, while education in LOGO and microPROLOG prepares them for the computers of the eighties and the nineties.</em></p>
<p>I can&#8217;t help but be a little moved by such unbridled enthusiasm! What went wrong? When I went to middle-school they didn&#8217;t even teach us a Basic dialect! Perhaps it&#8217;s time to revitalize the grand plans of microPROLOG and create a new generation of Prolog hackers?</p>
<p>Finally, I feel obliged to post one final picture from the book. It&#8217;s referred to as <em>The computer controlled home</em>, and should speak for itself.</p>
<p><a href="http://prologomenon.files.wordpress.com/2011/05/p4240084_small1.jpg"><img class="alignnone size-full wp-image-355" title="OLYMPUS DIGITAL CAMERA" src="http://prologomenon.files.wordpress.com/2011/05/p4240084_small1.jpg?w=519" alt=""   /></a></p>
<p>Man, the future is such a letdown!</p>
<p>(For the record, the next installment regarding computer generated music will probably be delayed for a few weeks due to an upcoming examination period.)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/346/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=346&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/05/13/mullets-moustaches-and-microprolog/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>

		<media:content url="http://prologomenon.files.wordpress.com/2011/05/p4240082_small.jpg?w=300" medium="image">
			<media:title type="html">OLYMPUS DIGITAL CAMERA</media:title>
		</media:content>

		<media:content url="http://prologomenon.files.wordpress.com/2011/05/p4240084_small1.jpg" medium="image">
			<media:title type="html">OLYMPUS DIGITAL CAMERA</media:title>
		</media:content>
	</item>
		<item>
		<title>Prolog&#8217;s Makin&#8217; Music &#8211; Part 1</title>
		<link>http://prologomenon.wordpress.com/2011/05/04/prologs-makin-music-part-1/</link>
		<comments>http://prologomenon.wordpress.com/2011/05/04/prologs-makin-music-part-1/#comments</comments>
		<pubDate>Wed, 04 May 2011 19:05:01 +0000</pubDate>
		<dc:creator>victorlagerkvist</dc:creator>
				<category><![CDATA[Logic programming]]></category>
		<category><![CDATA[Logtalk]]></category>
		<category><![CDATA[Music]]></category>
		<category><![CDATA[Prolog]]></category>

		<guid isPermaLink="false">http://prologomenon.wordpress.com/?p=307</guid>
		<description><![CDATA[Interlude Gather around everyone, and I&#8217;ll tell the story of how I sold my soul to the binary devil. It all began a dark and gloomy night. I&#8217;ve had one too many to drink &#8211; coffee, that is &#8211; and found it hard to concentrate on anything else than the splashing rain. The murky light [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=307&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Interlude</h3>
<p>Gather around everyone, and I&#8217;ll tell the story of how I sold my soul to the binary devil.</p>
<p>It all began a dark and gloomy night. I&#8217;ve had one too many to drink &#8211; coffee, that is &#8211; and found it hard to concentrate on anything else than the splashing rain. The murky light played tricks on my eyes, or so I thought. Dangling contours everywhere. The buzzing monitor didn&#8217;t help either. I stretched out my back with a loud, cracking sound and tried to suppress a yawn.</p>
<p>&#8220;Do you want the power to create music from thin air?&#8221;</p>
<p>A voice from nowhere. Surely I hadn&#8217;t had <em>that</em> much to drink. I held up my keyboard like a club, cursing myself for getting rid of the IBM model M keyboard in favor of an ergonomic one, and slowly turned my head in the direction of the voice. If there was an intruder, I wouldn&#8217;t go down without a fight.</p>
<p>&#8220;Who&#8217;s there?&#8221;, I cried.</p>
<p>After a long silence the voice finally answered:</p>
<p>&#8220;Do you want to make a deal?&#8221;</p>
<p>&#8220;A deal?!&#8221; I blurted out, getting rather annoyed by his impudence.</p>
<p>&#8220;I shall grant your computer the gift of making music. All I ask in return is that your next blog entry contains some steamy, bit-on-bit action that somehow involves the WAV format. Also, I shall need your soul for all eternity.&#8221;</p>
<p>Having run out of ideas, I had no choice but to accept his offer.</p>
<p>&#8220;Sure! Wait, no!&#8230; Who are you?&#8221;</p>
<p>A manic laughter followed. He vanished in a hazy puff of smoke and left. All that remained was a chilly wind and a feeling that I had somehow been cheated.</p>
<h3>Computer generated music</h3>
<p>Now to the point: the goal of this and the following entries will be to create computer generated music in Prolog/Logtalk. That might sound (pun not intended &#8211; I can&#8217;t help it) like a tall order, but hopefully everything will become clearer once we&#8217;ve explicated some of the concepts in music theory. The outline is as follows:</p>
<ul>
<li>Step 1 &#8211; Generate audio.</li>
<li>Step 2 &#8211; Generate tones from audio.</li>
<li>Step 3 &#8211; Generate melodies from tones, with a suitable formalism such as a cellular automata or an L-system.</li>
</ul>
<h3>Sound as oscillations</h3>
<p>In order to generate music we first need to understand what sound is. Wikipedia says:</p>
<blockquote><p><strong>Sound is a mechanical wave that is an oscillation of pressure transmitted through a solid, liquid, or gas, composed of frequencies within the range of hearing and of a level sufficiently strong to be heard, or the sensation stimulated in organs of hearing by such vibrations.</strong></p></blockquote>
<p>Or to put it a bit more pragmatic: a sound is a series of frequencies. Of course, this is a bit too simplistic to be useful in practice. Among other things, we need to decide whether we&#8217;re interested in mono or stereo sound, how fine-grained each frequency should be and how fast they should be played.</p>
<p>So we have an idea of how sound should be represented. First we decide how it should be interpreted by the listener, and then we give out the actual frequencies. As one might suspect there exists a myriad of different formats for this purpose. One of the simplest is the <a href="http://en.wikipedia.org/wiki/WAV" target="_blank">WAV</a> format, which we shall use in this project.</p>
<h3>Writing to binary files</h3>
<p>WAV is a binary format, and thus consists of a sequence of integers of varying sizes. Hence the first step is to learn how one writes to binary files in Prolog. The bad news is that there only exists one ISO primitive for this purpose: <img src='http://s0.wp.com/latex.php?latex=put%5C_byte%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='put&#92;_byte/2' title='put&#92;_byte/2' class='latex' />, which is not sufficient since it only works for single byte, signed integers. The good news is that we can get it to do what we want with some low-level bit-fiddling. Here&#8217;s the operations that we&#8217;ll need in order to produce a fully functional WAV file:</p>
<ul>
<li>Write 4 byte, unsigned integers in <a href="http://en.wikipedia.org/wiki/Endianness" target="_blank">big endian</a> format.</li>
<li>Write 4 byte, unsigned integers in little endian format.</li>
<li>Write 2 byte, unsigned integers in little endian format.</li>
<li>Write 2 byte, signed integers in little endian format.</li>
</ul>
<p>It would be nice if we could handle this in a uniform way, so that the underlying details of how one should use <img src='http://s0.wp.com/latex.php?latex=put%5C_byte%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='put&#92;_byte/2' title='put&#92;_byte/2' class='latex' /> can be postponed as far as possible. For this purpose we&#8217;ll introduce a data structure, <img src='http://s0.wp.com/latex.php?latex=word&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='word' title='word' class='latex' />, that has the format:</p>
<p><img src='http://s0.wp.com/latex.php?latex=word%28Byte%5C_Count%2C+Endian%2C+Integer%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='word(Byte&#92;_Count, Endian, Integer)' title='word(Byte&#92;_Count, Endian, Integer)' class='latex' /></p>
<p>where <img src='http://s0.wp.com/latex.php?latex=Byte%5C_Count&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Byte&#92;_Count' title='Byte&#92;_Count' class='latex' /> is either <img src='http://s0.wp.com/latex.php?latex=2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='2' title='2' class='latex' /> or <img src='http://s0.wp.com/latex.php?latex=4&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='4' title='4' class='latex' />, <img src='http://s0.wp.com/latex.php?latex=Endian&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Endian' title='Endian' class='latex' /> is either <img src='http://s0.wp.com/latex.php?latex=big&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='big' title='big' class='latex' /> or <img src='http://s0.wp.com/latex.php?latex=little&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='little' title='little' class='latex' />, and <img src='http://s0.wp.com/latex.php?latex=Integer&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Integer' title='Integer' class='latex' /> is a positive or negative integer. So to represent the number <img src='http://s0.wp.com/latex.php?latex=135&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='135' title='135' class='latex' />  in the little endian format we would use:</p>
<p><img src='http://s0.wp.com/latex.php?latex=word%282%2C+little%2C+135%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='word(2, little, 135)' title='word(2, little, 135)' class='latex' /></p>
<p>while the number 1350 in big endian format would represented as:</p>
<p><img src='http://s0.wp.com/latex.php?latex=word%284%2C+big%2C+1350%29&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='word(4, big, 1350)' title='word(4, big, 1350)' class='latex' /></p>
<p>Simple, but it might feel kind of weird to represent such a low-level concept in this way. In most imperative languages we would of course explicitly declare the data as either char, short, int and so on, but this is the best we can do in Prolog (unless we create necessary bindings for the host language and borrow some datatypes). Next, we&#8217;re going to define <img src='http://s0.wp.com/latex.php?latex=write%5C_word%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='write&#92;_word/2' title='write&#92;_word/2' class='latex' /> that writes a word to a stream. Let&#8217;s focus on 2 byte integers for the moment. A first attempt might look like:</p>
<p><pre class="brush: plain;">
write_word(word(2, Endian, I), Stream) :-
    put_byte(Stream, I).
</pre></p>
<p>Alas, this only works for single byte integers. If we want to write 2 bytes, we need to extract the individual bytes from the integer and call <img src='http://s0.wp.com/latex.php?latex=put%5C_byte%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='put&#92;_byte/2' title='put&#92;_byte/2' class='latex' /> two times. This can be done with shifting and the bitwise and-operation.</p>
<p><pre class="brush: plain;">
write_word(word(2, Endian, Bs), S) :-
    X1 is Bs &gt;&gt; 8,
    X2 is Bs /\ 0x00ff,
    (  Endian = big -&gt;
       put_byte(S, X1),
       put_byte(S, X2)
    ;  put_byte(S, X2),
       put_byte(S, X1)
    ).
</pre></p>
<p>Note that we also check whether <img src='http://s0.wp.com/latex.php?latex=Endian&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='Endian' title='Endian' class='latex' /> is <img src='http://s0.wp.com/latex.php?latex=big&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='big' title='big' class='latex' />, and if so output the bytes in reversed order. This works fine for positive numbers, but what about signed, negative numbers? Since <img src='http://s0.wp.com/latex.php?latex=put%5C_byte%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='put&#92;_byte/2' title='put&#92;_byte/2' class='latex' /> only works with positive numbers, we need to convert the negative number into a positive number that is still negative with respect to that byte range. This is actually rather easy to do since we&#8217;re using <a href="http://en.wikipedia.org/wiki/Two's_complement" target="_blank">two&#8217;s complement numbers</a>: if the number is negative, then add  a number such that the sum is the two&#8217;s complement of the absolute value of the negative number. The code will make this easier to understand:</p>
<p><pre class="brush: plain;">
    write_word(word(2, Endian, Bs), S) :-
        Bs &gt;= 0,
        X1 is Bs &gt;&gt; 8,
        X2 is Bs /\ 0x00ff,
        (  Endian = big -&gt;
           put_byte(S, X1),
           put_byte(S, X2)
        ;  put_byte(S, X2),
           put_byte(S, X1)
        ).
    write_word(word(2, Endian, Bs), S) :-
        Bs &lt; 0,
        Bs1 is Bs + 0xffff,
        write_word(word(2, Endian, Bs1), S).
</pre></p>
<p>(Thanks to Pierpaolo Bernardi who showed me this trick on the SWI-Prolog mailing list!)<br />
Update: Richard O&#8217;Keefe also showed a simpler solution that doesn&#8217;t need the explicit positive/negative test. It&#8217;s left as an exercise to the reader!</p>
<p>The code for 4 byte integers is rather similar and hence omitted.</p>
<h3>The WAV format</h3>
<p>Now let&#8217;s focus on WAV. All my knowledge of the format stems from a single <a href="https://ccrma.stanford.edu/courses/422/projects/WaveFormat/" target="_blank">source</a> (click for a useful, visual diagram). A WAV file consists of:</p>
<ul>
<li>A header containing the string &#8220;RIFF&#8221;, the remaining chunk size and the string &#8220;WAVE&#8221;.</li>
<li>A format subchunk containing the string &#8220;fmt&#8221; (format), the remaining chunk size, the audio format, the number of channels, the sample rate, the byte rate, the block align and the number of bits that are used for each sample.</li>
<li>A data subchunk that contains the string &#8220;data&#8221;, the remaining size of the subchunk and finally the actual data (the samples).</li>
</ul>
<p>Don&#8217;t worry if some of these terms are unfamiliar or confusing. It&#8217;s not necessary to understand all the details. We begin by defining the number of samples, the number of channels, the bits per sample and the sample rate as facts:</p>
<p><pre class="brush: plain;">
    num_samples(100000). %This value will of course differ depending on the audio data.
    num_channels(1). %Mono.
    bits_per_sample(16). %Implies that each sample is a 16 bit, signed integer.
    sample_rate(22050).
</pre></p>
<p>All the other values can be derived from these parameters. For simplicity we&#8217;re going to produce a list of words that are later written with the help of <img src='http://s0.wp.com/latex.php?latex=write%5C_word%2F2&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='write&#92;_word/2' title='write&#92;_word/2' class='latex' />. This can be done in any number of ways, but DCG&#8217;s are fairly straightforward in this case. The RIFF chunk is first. It takes the size of the data chunk as argument since it is needed in order to produce the size of the remaining chunk.</p>
<p><pre class="brush: plain;">
    riff_chunk(Data_Chunk_Size) --&gt;
        riff_string,
        chunk_size(Data_Chunk_Size),
        wave_string.

    riff_string --&gt; [word(4, big, 0x52494646)].
    wave_string --&gt; [word(4, big, 0x57415645)].

    chunk_size(Data_Chunk_Size) --&gt;
        {Size is Data_Chunk_Size + 36}, % Magic constant!
        [word(4, little, Size)].
</pre></p>
<p>The end result will be a list of the form <img src='http://s0.wp.com/latex.php?latex=%5Bword%284%2C+big%2C+0x52494646%29%2C+...%5D&amp;bg=efefef&amp;fg=555555&amp;s=0' alt='[word(4, big, 0x52494646), ...]' title='[word(4, big, 0x52494646), ...]' class='latex' />. The format chunk follows the same basic structure:</p>
<p><pre class="brush: plain;">
fmt_chunk --&gt;
    fmt_string,
    sub_chunk1_size,
    audio_format,
    number_of_channels,
    sample_rate,
    byte_rate,
    block_align,
    bits_per_sample.

fmt_string --&gt;  [word(4, big, 0x666d7420)]. %&quot;fmt&quot;.

sub_chunk1_size --&gt; [word(4, little, 16)]. %16, for PCM.

audio_format --&gt; [word(2, little, 1)]. %PCM.

number_of_channels --&gt;
    [word(2, little, N)],
    {num_channels(N)}.

.
.
. % And so on for all the remaining stuff.
</pre></p>
<p>The remaining data chunk is even simpler:</p>
<p><pre class="brush: plain;">
data_chunk(Data_Chunk_Size) --&gt;
    data_string,
    [word(4, little, Data_Chunk_Size)],
    test_data.

test_data --&gt; ... %This should generate a list of samples.
</pre></p>
<p>And finally, we say that a WAV file consists of a riff chunk, an fmt chunk and a data chunk:</p>
<p><pre class="brush: plain;">
    wav_file --&gt;
        {num_samples(N),
         bits_per_sample(BPS),
         num_channels(Cs),
         Data_Chunk_Size is N*BPS*Cs/8},
        riff_chunk(Data_Chunk_Size),
        fmt_chunk,
        data_chunk(Data_Chunk_Size).
</pre></p>
<p>It is used in the following way:</p>
<p><pre class="brush: plain;">
    output(File) :-
        open(File, write, S, [type(binary)]),
        %Call the DCG, get a list of words as result.
        phrase(wav_file, Data),
        %Write the list of words.
        write_data(Data, S),
        close(S).

    write_data([], _).
    write_data([B|Bs], S) :-
        write_word(B, S),
        write_data(Bs, S).
</pre></p>
<p>As test data, we&#8217;re going to generate a 440HZ sine wave.</p>
<p><pre class="brush: plain;">
    sine_wave(0) --&gt; [].
    sine_wave(N) --&gt;
        {N &gt; 0,
        sample_rate(SR),
        N1 is N - 1,
        %% Standard concert pitch, 440 Hz.
        Freq is 440,
        ScaleFactor is 2*pi*Freq/SR,
        %% Needed since sin(X) returns an integer in [-1, 1], which
        %% is barely (if at all) perceivable by the human ear. The
        %% constant 32767 is used since we're dealing with 16 bit,
        %% signed integers, i.e. the range of the samples is [-32768,
        %% 32767].
        VolumeFactor is 32767,
        X is ScaleFactor*N,
        Sample0 is sin(X),
        %% Floor the sample. Otherwise we would end up with a floating
        %% point number, which is not allowed.
        Sample is floor(Sample0*VolumeFactor)},
        [word(2, little, Sample)],
        sine_wave(N1).
</pre></p>
<p>It&#8217;s not necessary to understand all the details, but the end result is a list of 2 byte words that represent a 440 HZ sine wave. You can listen to it <a href="http://soundcloud.com/prologomenon/sine-wave">here</a>.</p>
<h3>Summary</h3>
<p>We&#8217;re now able to write samples to WAV files. These samples can represent any tone or sound, so in theory we already have everything that&#8217;s needed to generate music. But representing a tune as millions and millions of samples is not very user-friendly and would make it more or less impossible to automatically generate anything interesting. For that we&#8217;re going to need further abstractions, and among other things define a sound bank that contains some common tones.</p>
<h3>Source code</h3>
<p>The source code is available at <a href="https://gist.github.com/955626">https://gist.github.com/955626</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prologomenon.wordpress.com/307/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prologomenon.wordpress.com/307/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prologomenon.wordpress.com/307/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prologomenon.wordpress.com/307/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prologomenon.wordpress.com/307/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prologomenon.wordpress.com/307/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prologomenon.wordpress.com/307/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prologomenon.wordpress.com/307/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prologomenon.wordpress.com/307/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prologomenon.wordpress.com/307/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prologomenon.wordpress.com/307/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prologomenon.wordpress.com/307/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prologomenon.wordpress.com/307/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prologomenon.wordpress.com/307/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prologomenon.wordpress.com&amp;blog=19761547&amp;post=307&amp;subd=prologomenon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prologomenon.wordpress.com/2011/05/04/prologs-makin-music-part-1/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/10357ee3398a825bd7c953f3b59e81db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">victorlagerkvist</media:title>
		</media:content>
	</item>
	</channel>
</rss>
