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

<channel>
	<title>niche computing science</title>
	<atom:link href="http://www.iis.sinica.edu.tw/~scm/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.iis.sinica.edu.tw/~scm</link>
	<description>Research Blog of 穆信成 Shin-Cheng Mu</description>
	<lastBuildDate>Mon, 21 Nov 2011 11:53:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Proving the Church-Rosser Theorem Using a Locally Nameless Representation</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2011/proving-the-church-rosser-theorem/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2011/proving-the-church-rosser-theorem/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 11:53:29 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Research Blog]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=557</guid>
		<description><![CDATA[Around 2 years ago, for an earlier project of mine (which has not seen its light yet!) in which I had to build a language with variables and prove its properties, I surveyed a number of ways to handle binders. For some background, people have noticed that, when proving properties about a language with bound [...]]]></description>
			<content:encoded><![CDATA[<p>Around 2 years ago, for an earlier project of mine (which has not seen its light yet!) in which I had to build a language with variables and prove its properties, I surveyed a number of ways to handle binders. For some background, people have noticed that, when proving properties about a language with bound variables, one often ends up spending most of the effort proving &#8220;uninteresting&#8221; things about names, substitution, weakening, etc. For formal theorem proving to be practical, the effort has to be reduced. A number of approaches were proposed. Among them, the &#8220;locally nameless&#8221; style appeared to be interesting and promising. </p>
<p>With the only reference I used, <a href="#1">Engineering Formal Metatheory</a> by Aydemir et al., which outlines the principle ideas of the approach, I imagined how it works and tried to implement my own version in Agda. My first few implementations, however, all ended up in a mess. It appeared that there was an endless number of properties to prove. Besides the complexity of the language I was implementing, there must be something I got wrong about the locally nameless representation. Realising that I could not finish the project this way, I eventually decided to learn from the basics.</p>
<p>I started with the <a href="#2">tutorial by Chargueraud</a>, with <a href="http://www.chargueraud.org/softs/ln/index.php">complete code in Coq</a>. I would then follow his footprints using Agda. The task is a classical one: define untyped λ-calculus and its reduction rules, and prove the Church-Rosser theorem.</p>
<h3>Term</h3>
<p>From an abstract level, there is nothing too surprising. We define a syntax for untyped λ-calculus that distinguishes between free and bound variables:<br />
<code>
<pre>data Term : Set where
  bv : (i : BName) → Term
  fv : (x : FName) → Term
  ƛ : (e : Term) → Term
  _·_ : (e₁ : Term) → (e₂ : Term) → Term</pre>
<p></code> where <code>BName = ℕ</code> represents bound variables by de Bruin indexes, while <code>FName</code> is the type of free variables. The latter can be any type that supports equality check and a method that generates a new variable not in a given set (in fact, a <code>List</code>) of variables. If one takes <code>FName = String</code>, the expression <code>λ x → x y</code>, where <code>y</code> occurs free, is represented by <code>ƛ (bv 0 · fv "y")</code>. For ease of implementation, one may take<code>FName = ℕ</code> as well.</p>
<p>Not all terms you can build are valid. For example, <code>ƛ (bv 1 · fv "y")</code> is not a valid term since there is only one <code>ƛ</code> binder. How to distinguish the valid terms from invalid ones? I would (and did) switch to a dependent datatype <code>Term n</code>, indexed by the number of enclosing binders, and let <code>BName = Fix n</code>. The index is passed top-down and is incremented each time we encounter a <code>ƛ</code>. Closed terms are then represented by the type <code>Term 0</code>.</p>
<p>The representation above, if works, has the advantage that a term that can be build at all must be valid. Choosing such a representation was perhaps the first thing I did wrong, however. Chargueraud mentioned a similar predicate that also passes the &#8220;level&#8221; information top-down, and claimed that the predicate, on which we will have to perform induction on to prove property about terms, does not fit the usual pattern of induction. This was probably why I had so much trouble proving properties about terms.</p>
<p>The way to go, instead, is to use a predicate that assembles the information bottom up. The predicate <code>LC</code> (&#8220;locally-closed&#8221; &#8212; a term is valid if it is locally closed) is defined by:<br />
<code>
<pre>data LC : Term → Set where
  fv : ∀ x → LC (fv x)
  ƛ : (L : FNames) → ∀ {e} →
       (fe : ∀ {x} → (x∉L : x ∉ L) → LC ([ 0 ↦ fv x ]  e)) → LC (ƛ e)
  _·_ : ∀ {e₁ e₂} → LC e₁ → LC e₂ → LC (e₁ · e₂)</pre>
<p></code>A free variable alone is a valid term. A application <code>f · e</code> is valid if both <code>f</code> and <code>e</code> are. And an abstraction <code>ƛ e</code> is valid if <code>e</code> becomes a valid term after we substitute any free variable <code>x</code> for the first (<code>0</code>-th) bound variable. There can be an additional constraint on <code>x</code>, that it is not in <code>L</code>, a finite set of &#8220;protected&#8221; variables &#8212; such <em>co-finite</em> quantification is one of the features of the locally nameless style.</p>
<p>The &#8220;open&#8221; operator <code>[ n ↦ t ]  e</code> substitutes the term <code>t</code> for the <code>n</code>-th bound variable in <code>e</code>. It is defined by<br />
<code>
<pre>[_↦_] : ℕ → Term → Term → Term
[ n ↦ t ] (bv i) with n ≟ i
...        | yes _ = t
...        | no _ = bv i
[ n ↦ t ] (fv y) = fv y
[ n ↦ t ] (ƛ e) = ƛ ([ suc n ↦ t ] e)
[ n ↦ t ] (e₁ · e₂) = [ n ↦ t ] e₁ · [ n ↦ t ] e₂</pre>
<p></code>note how <code>n</code> is incremented each time we go into a <code>ƛ</code>. A dual operator,<br />
<code>
<pre>[_↤_] : ℕ → FName → Term → Term</pre>
<p></code>instantiates the <code>n</code>-th bound variable to a term.</p>
<h3>β Reduction and Church-Rosser Theorem</h3>
<p>Small-step β reduction can be defined by:<br />
<code>
<pre>data _β→_ : Term → Term → Set where
  β-red : ∀ {t₁ t₂} → Body t₁ → LC t₂
          → ((ƛ t₁) · t₂) β→ [ 0 ↦ t₂ ] t₁
  β-app₁ : ∀ {t₁ t₁' t₂} → LC t₂
           → t₁ β→ t₁'
           → (t₁ · t₂) β→ (t₁' · t₂)
  β-app₂ : ∀ {t₁ t₂ t₂'} → LC t₁
           → t₂ β→ t₂'
           → (t₁ · t₂) β→ (t₁ · t₂')
  β-ƛ : ∀ L {t₁ t₁'}
           → (∀ x → x ∉ L → ([ 0 ↦ fv x ] t₁) β→ ([ 0 ↦  fv x ] t₁'))
           → ƛ t₁ β→ ƛ t₁'</pre>
<p></code>where <code>β-red</code> reduces a redux, <code>β-app₁</code> and <code>β-app₂</code> allows reduction respectively on the right and left hand sides of an application, and <code>β-ƛ</code> goes into a <code>ƛ</code> abstraction &#8212; again we use co-finite quantification. </p>
<p>Given <code>_β→_</code> we can define its reflexive, transitive closure <code>_β→*_</code>, and the reflexive, transitive, symmetric closure <code>_β≣_</code>. The aim is to prove that <code>_β→*_</code> is confluent:<br />
<code>
<pre>β*-confluent :
  ∀ {m s t} → (m β→* s) → (m β→* t)
                  → ∃ (λ u → (s β→* u) × (t β→* u))</pre>
<p></code>which leads to the Church-Rosser property:<br />
<code>
<pre>β-Church-Russer : ∀ {t₁ t₂} → (t₁ β≣ t₂)
                    → ∃ (λ t → (t₁ β→* t) × (t₂ β→* t))
</pre>
<p></code></p>
<p>At an abstract level, the proof follows the classical route: it turns out that it is easier to prove the confluence of a &#8220;parallel reduction&#8221; relation <code>_⇉_</code> which allows β reduction to happen in several places of a term in one step. We then prove that <code>_β→*_</code> is equivalent to <code>_⇉*_</code>, thereby proving the confluence of <code>_β→*_</code> as well. All these can be carried out relatively nice and clean.</p>
<p>The gory details, however, hides in proving the infrastructutal properties supporting the abstract view of the proofs.</p>
<h3>Infrastructures</h3>
<p>Confluence, Church-Rosser&#8230; these are the interesting stuffs we <em>want</em> to prove. However, we often end up spending most of the time proving those infrastructure properties we <em>have</em> to prove &#8212; which is why there have been so much recent research hoping to find better representations that simplify them. The locally nameless style is supposed to be such a representation. (Another orthogonal topic is to seek generic representations such that the proofs can be done once for all languages.)</p>
<p>In my code, most of these properties are piled in the file <code>Infrastructure.agda</code>. They range from  stuffs you might expect to have:<br />
<code>
<pre>open-term : ∀ k t {e} → LC e → e ≡ [ k ↦ t ] e
close-var-open-aux : ∀ k x e → LC e → e ≡ [ k ↦ fv x ] ([ k ↤ x ] e)</pre>
<p></code>to stuffs not that obvious:<br />
<code>
<pre>open-var-inj : ∀ k x t u → x ∉ fvars t → x ∉ fvars u
               → [ k ↦ fv x ] t ≡ [ k ↦ fv x ] u → t ≡ u
open-term-aux : ∀ j t i u e → ¬ (i ≡ j)
                → [ j ↦ t ] e ≡ [ i ↦ u ] ([ j ↦ t ] e)
                → e ≡ [ i ↦ u ] e</pre>
<p></code>The lemma <code>open-var-inj</code> is one of the early lemmas that appeared in <a name="2">Chargueraud&#8217;s tutorial</a>, which might give one the impression that it is an easy first lemma to prove. On the contrary, it is among the tedious ones &#8212; I needed a 40-line proof (most of the cases were simply eliminated by contraction, though).</p>
<p>It takes experience and intuition to know what lemmas are needed. Without promise that it will work, I would think something must have gone wrong when I found myself having to prove weird looking lemmas like:<br />
<code>
<pre>close-var-rec-open :
  ∀ x y z t i j
  → ¬(i ≡ j) → ¬(y ≡ x) → y ∉ fvars t
  → [ i ↦ fv y ] ([ j ↦ fv z ] ([ j ↤ x ] t))
    ≡ [ j ↦ fv z ] ([ j ↤ x ] ([ i ↦ fv y ] t))</pre>
<p></code>which is not easy to prove either.</p>
<h3>The Bottom Line?</h3>
<p>So, is the locally nameless representation what it claims to be &#8212; a way to represent binders that simplifies the infrastructural proofs and is easier to scale up? When I was struggling with some of the proofs in <code>Infrastructure.agda</code> I did wonder whether the claim is true only for Coq, with cleverly designed proof tactics, but not for Agda, where everything is done by hand (so far). Once the infrastructural proofs are done, however, the rest was carried out very pleasantly.</p>
<p>To make a fair comparison, I should re-implement everything again using de Bruin notation. That has to wait till some other time, though. (Any one want to give it a try?)</p>
<p>It could be the case that, while some proofs are easily dismissed in Coq using tactics, in Agda the programmer should develop some more abstractions. I did feel myself repeating some proof patterns, and found one or two lemmas that do not present in Chargueraud&#8217;s tutorial which, if used in Agda, simplifies the proofs a bit. There could be more, but at this moment I am perhaps too involved in the details to see the patterns from a higher viewpoint.</p>
<p>The exercise does pay off, though. Now I feel I am much more familiar with this style, and am perhaps more prepared to use it in my own project.</p>
<h3>Code</h3>
<p>A <a href="http://www.iis.sinica.edu.tw/~scm/sw/LocallyNamelessCore.zip">zip</a> file containing all the code.</p>
<h3>References</h3>
<ol>
<li><a name="1"></a>Brian Aydemir, Arthur Chargueraud,  Benjamin Pierce, Randy Pollack, and Stephanie Weirich. Engineering Formal Metatheory. POPL &#8217;08.</li>
<li><a name="2"></a>Arthur Chargueraud. The Locally Nameless Representation. <i>Journal of Automated Reasoning</i>, May 2011</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2011/proving-the-church-rosser-theorem/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Constructing list homomorphisms from proofs</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2011/constructing-list-homomorphisms-from-proofs/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2011/constructing-list-homomorphisms-from-proofs/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 12:40:13 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Conference]]></category>
		<category><![CDATA[Publication]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=554</guid>
		<description><![CDATA[Yun-Yan Chi and Shin-Cheng Mu. Constructing list homomorphisms from proofs. In the <i>9th Asian Symposium on Programming Languages and Systems</i> (APLAS 2011). [<a href="http://www.iis.sinica.edu.tw/~scm/pub/thr.pdf">PDF</a>]]]></description>
			<content:encoded><![CDATA[<p>Yun-Yan Chi and Shin-Cheng Mu. In the <i>9th Asian Symposium on Programming Languages and Systems</i> (APLAS 2011). [<a href="http://www.iis.sinica.edu.tw/~scm/pub/thr.pdf">PDF</a>]</p>
<p>The well-known third list homomorphism theorem states that if a function <code>h</code> is both an instance of <code>foldr</code> and <code>foldl</code>, it is a list homomorphism. Plenty of previous works devoted to constructing list homomorphisms, however, overlook the fact that proving <code>h</code> is both a <code>foldr</code> and a <code>foldl</code> is often the hardest part which, once done, already provides a useful hint about what the resulting list homomorphism could be. In this paper we propose a new approach: to construct a possible candidate of the associative operator and, at the same time, to transform a <em>proof</em> that <code>h</code> is both a <code>foldr</code> and a <code>foldl</code> to a proof that <code>h</code> is a list homomorphism.  The effort constructing the proof is thus not wasted, and the resulting program is guaranteed to be correct.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2011/constructing-list-homomorphisms-from-proofs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generalising and dualising the third list-homomorphism theorem</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2011/generalising-and-dualising-the-third-list-homomorphism-theorem/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2011/generalising-and-dualising-the-third-list-homomorphism-theorem/#comments</comments>
		<pubDate>Thu, 08 Sep 2011 08:31:32 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Conference]]></category>
		<category><![CDATA[Publication]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=549</guid>
		<description><![CDATA[Shin-Cheng Mu and <a href="http://www.riec.tohoku.ac.jp/~morihata/">Akimasa Morihata</a>. Generalising and dualising the third list-homomorphism theorem. In the <i>16th ACM SIGPLAN International Conference on Functional Programming</i> (ICFP 2011). 
[<a href="http://www.iis.sinica.edu.tw/~scm/pub/icfp055fp-mu.pdf">PDF</a>]
]]></description>
			<content:encoded><![CDATA[<p>Shin-Cheng Mu and <a href="http://www.riec.tohoku.ac.jp/~morihata/">Akimasa Morihata</a>. In the <i>16th ACM SIGPLAN International Conference on Functional Programming</i> (ICFP 2011).<br />
[<a href="http://www.iis.sinica.edu.tw/~scm/pub/icfp055fp-mu.pdf">PDF</a>]</p>
<p>The third list-homomorphism theorem says that a function is a list homomorphism if it can be described as an instance of both a <code>foldr</code> and a <code>foldl</code>. We prove a dual theorem for unfolds and generalise both theorems to trees: if a function generating a list can be described both as an <code>unfoldr</code> and an <code>unfoldl</code>, the list can be generated from the middle, and a function that processes or builds a tree both upwards and downwards may independently process/build a subtree and its one-hole context. The point-free, relational formalism helps to reveal the beautiful symmetry hidden in the theorem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2011/generalising-and-dualising-the-third-list-homomorphism-theorem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calculating Programs from Galois Connections</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2010/calculating-programs-from-galois-connections/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2010/calculating-programs-from-galois-connections/#comments</comments>
		<pubDate>Fri, 10 Dec 2010 03:22:11 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Research Blog]]></category>
		<category><![CDATA[Galois Connection]]></category>
		<category><![CDATA[Program Derivation]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=523</guid>
		<description><![CDATA[One is often amazed that, once two functions are identified as a Galois connection, a long list of nice and often useful properties follow from one concise, elegant defining equation. But how does one construct a program from a specification given as a Galois connection?]]></description>
			<content:encoded><![CDATA[<p>Galois connections are ubiquitous in mathematics and computing science. One is often amazed that, once two functions are identified as a Galois connection, a long list of nice and often useful properties follow from one concise, elegant defining equation. But how does one construct a program from a specification given as a Galois connection? This is the topic of <a href="http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections/">a recent work</a> of José Nuno Oliveira and I, and this article is an advertisement.</p>
<h3>Galois Connections as Specifications</h3>
<p>In program construction one often encounters program specification of the form &#8220;&#8230; the smallest such number&#8221;, &#8220;the longest prefix of the input list satisfying &#8230;&#8221;, etc. A typical example is whole number division: given a natural number <code>x</code> and a positive integer <code>y</code>, <code>x / y</code> is the largest natural number that, when multiplied by <code>y</code>, is at most <code>x</code>. For another example, the Haskell function <code>takeWhile p</code> returns the longest prefix of the input list such that all elements satisfy predicate <code>p</code>.</p>
<p>Such specifications can be seen as consisting of two parts. The <em>easy part</em> specifies a collection of solution candidates: numbers that are at most <code>x</code> after multiplication with <code>y</code>, or all prefixes of the input list. The <em>hard</em> part, on the other hand, picks one optimal solution, such as the largest, the longest, etc., among the collection. </p>
<p>Our goal is to calculate programs for such specifications. But how best should the specification be given in the first place? Take division for example, one might start from a specification that literally translates our description above into mathematics:<br />
<code>
<pre>    x / y = ⋁{ z | z * y ≤ x } </pre>
<p></code>As we know, however, suprema is in general not easy to handle. One could also explicitly name the remainder:<br />
<code>
<pre>    z = x / y  ≡  (∃ r : 0 ≤ r < y : x = z * y + r)</pre>
<p></code>at the cost of existentially quantifying over the remainder.</p>
<p>A third option looks surprising simpler: given <code>x</code> and <code>y</code>, the value <code>x / y</code> is such that for all <code>z</code>,<br />
<code>
<pre>    z * y ≤ x  ≡  z ≤ x / y<span style="float:right">(1)</span></pre>
<p></code>Why is this sufficient as a definition of <code>x / y</code>? Firstly, by substituting <code>x / y</code> for <code>z</code>, the right hand side of <code>≡</code> reduces to true, and we obtain on the left hand side <code>(x / y) * y ≤ x</code>. This tell that <code>x / y</code> is a candidate --- it satisfies the easy part of the specification. Secondly, read the definition from left to right: <code>z * y ≤ x  ⇒ z ≤ x / y</code>. It says that <code>x / y</code> is the largest among all the numbers satisfying the easy part.</p>
<p>Equations of the form are called <em>Galois connections</em>. Given preorders <code>⊑</code> and <code>≤</code>, Functions <code>f</code> and <code>g</code> form a Galois connection if for all <code>x</code> and <code>z</code> we have<br />
<code>
<pre>    f z ⊑ x  ≡  z ≤ g x<span style="float:right">(2)</span></pre>
<p></code>The function <code>f</code> is called the lower adjoint and <code>g</code> the upper adjoint. </p>
<p>The definition of division above is a Galois connection where <code>f = (* y)</code> and <code>g = (/ y)</code>. For another example, <code>takeWhile p</code> can be specified as an upper adjoint:<br />
<code>
<pre>    map p? zs ⊑ xs  ≡  zs ⊑ takeWhile p xs<span style="float:right">(3)</span></pre>
<p></code>where <code>⊑</code> is the prefix ordering: <code>ys ⊑ xs</code> if <code>ys</code> is a prefix of <code>xs</code>, and <code>map p?</code> is a partial function: <code>map p? xs = xs</code> if <code>p x</code> holds for each <code>x</code> in <code>xs</code>.</p>
<p>We love Galois connections because once two functions are identified as such, a long list of useful properties follows: <code>f (g x) ⊑ x</code>, <code>z ≤ g (f z)</code>, <code>f</code> and <code>g</code> are monotonic, and are inverses of each other in the other's range... etc.</p>
<p>These are all very nice. But can one calculate a program from a Galois connection? Given <code>⊑</code>, <code>≤</code>, and <code>f</code>, how does one construct <code>g</code>?</p>
<h3>The "Shrink" Operator</h3>
<p>José discovered and proposed a relational operator to handle such calculations. To use the operator, we have to turn the Galois connection <code>(1)</code> into point-free style. We look at the left hand side of <code>(1)</code>: <code>f z ⊑ x</code>, and try to write it as a relation between <code>z</code> and <code>x</code>. Let <code>f°</code> denote the relational converse of <code>f</code> -- roughly, think of it as the inverse function of <code>f</code>, that it, it maps <code>f z</code> to <code>z</code>, and let <code>∘</code> denote relational composition -- function composition extended to relations. Thus <code>f z ⊑ x</code> translates to<br />
<code>
<pre>    f° ∘ (⊑)</pre>
<p></code>It is a relation between <code>z</code> and <code>x</code>: putting <code>x</code> on the left hand side of <code>f° ∘ (⊑)</code>, it relates, through <code>⊑</code>, to <code>f z</code>, which is then mapped to <code>z</code> through <code>f°</code>.</p>
<p>Then we wish that <code>f° ∘ (⊑)</code> can be transformed into a (relational) fold or unfold, which is often the case because the defining components: <code>⊑</code>, <code>≤</code>, and <code>f</code>, are often folds or unfolds. Consider the lower adjoint of <code>takeWhile p</code> in <code>(3)</code>. Since <code>⊑</code>, the relation that takes a list and returns a prefix of the list, can be defined as a fold on lists, <code>(map p?)° ∘ (⊑)</code>, by fold fusion, is also a fold. Consider <code>(1)</code>, since <code>≤</code> and <code>(* y)</code> are both folds on natural numbers, <code>(* y)° ∘ (≤)</code> can be both a fold and an unfold.</p>
<p>In <a href="http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections/">our paper</a> we showed that a Galois connection <code>(2)</code> can be transformed into<br />
<code>
<pre>    g = (f° ∘ (⊑)) ↾ (≥)</pre>
<p></code>where <code>↾</code> is the new operator José introduced. The relation <code>S ↾ R</code>, pronounced "<code>S</code> shrunk by <code>R</code>", is a sub-relation of <code>S</code> that yields, for each input, an optimal result under relation <code>R</code>. Note that the equation made the easy/hard division explicit: <code>f° ∘ (⊑)</code> is the easy part: we want a solution <code>z</code> that satisfies <code>f z ⊑ x</code>, while <code>≥</code> is the criteria we use, in the hard part, to choose an optimal solution.</p>
<p>The <code>↾</code> operator is similar to the <code>min</code> operator of Bird and de Moor, without having to use sets (which needs a power allegory). It satisfies a number of useful properties. In particular, we have theorems stating when <code>(↾ R)</code> promotes into folds and unfolds. For example,<br />
<code>
<pre>    (fold S) ↾ R ⊇ fold (S ↾ R)</pre>
<p></code>if <code>R</code> is transitive and <code>S</code> is monotonic on <code>R</code>. </p>
<p>With the theorems we can calculate <code>g</code>. Given <code>g</code>, specified as an upper adjoint in a Galois connection with lower adjoint <code>f</code>, we first try to turn <code>f° ∘ (⊑)</code> into a fold or an unfold, and then apply the theorems to promote <code>(↾ (≥))</code>. For more details, take a look at <a href="http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections/">our paper</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2010/calculating-programs-from-galois-connections/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Programming from Galois connections &#8212; principles and applications</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections-principles-and-applications/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections-principles-and-applications/#comments</comments>
		<pubDate>Thu, 09 Dec 2010 08:01:55 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Publication]]></category>
		<category><![CDATA[Galois Connection]]></category>
		<category><![CDATA[Program Derivation]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=519</guid>
		<description><![CDATA[Shin-Cheng Mu and <a href="http://www3.di.uminho.pt/~jno/">José Nuno Oliveira</a>. Programming from Galois connections -- principles and applications. Technical Report TR-IIS-10-009, Academia Sinica, December 2010.
[<a href="http://www.iis.sinica.edu.tw/~scm/pub/gc-report.pdf">PDF</a>]]]></description>
			<content:encoded><![CDATA[<p>Shin-Cheng Mu and <a href="http://www3.di.uminho.pt/~jno/">José Nuno Oliveira</a>. Technical Report TR-IIS-10-009, Academia Sinica, December 2010.<br />
[<a href="http://www.iis.sinica.edu.tw/~scm/pub/gc-report.pdf">PDF</a>]</p>
<p>This report is an extended version of our conference submission <a href="http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections/">Programming from Galois connections</a>. </p>
<p>Problem statements often resort to superlatives such as in eg. &#8220;&#8230; the smallest such number&#8221;, &#8220;&#8230; the best approximation&#8221;, &#8220;&#8230; the longest such list&#8221; which lead to specifications made of two parts: one defining a broad class of solutions (the <em>easy</em> part) and the other requesting the optimal such solution (the <em>hard</em> part).</p>
<p>This report introduces a binary relational combinator which mirrors this linguistic structure and exploits its potential for calculating programs by optimization. This applies in particular to specifications written in the form of Galois connections, in which one of the adjoints delivers the optimal solution at target.</p>
<p>The framework encompasses re-factoring of results previously developed by Bird and de Moor for greedy and dynamic programming, in a way which makes them less technically involved and therefore easier to understand and play with.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections-principles-and-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming from Galois connections</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections/#comments</comments>
		<pubDate>Thu, 09 Dec 2010 07:58:02 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Conference]]></category>
		<category><![CDATA[Publication]]></category>
		<category><![CDATA[Galois Connection]]></category>
		<category><![CDATA[Program Derivation]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=515</guid>
		<description><![CDATA[Shin-Cheng Mu and <a href="http://www3.di.uminho.pt/~jno/">José Nuno Oliveira</a>. Programming from Galois connections. In the <i>12th International Conference on Relational and Algebraic Methods in Computer Science</i> (RAMiCS 12), May 30 - June 3, 2011.
[<a href="http://www.iis.sinica.edu.tw/~scm/pub/ramics11.pdf">PDF</a>]]]></description>
			<content:encoded><![CDATA[<p>Shin-Cheng Mu and <a href="http://www3.di.uminho.pt/~jno/">José Nuno Oliveira</a>. In the <i>12th International Conference on Relational and Algebraic Methods in Computer Science</i> (RAMiCS 12), May 30 &#8211; June 3, 2011.<br />
[<a href="http://www.iis.sinica.edu.tw/~scm/pub/ramics11.pdf">PDF</a>]</p>
<p>Problem statements often resort to superlatives such as in eg. &#8220;&#8230; the smallest such number&#8221;, &#8220;&#8230; the best approximation&#8221;, &#8220;&#8230; the longest such list&#8221; which lead to specifications made of two parts: one defining a broad class of solutions (the <em>easy</em> part) and the other requesting the optimal such solution (the <em>hard</em> part).</p>
<p>This paper introduces a binary relational combinator which mirrors this linguistic structure and exploits its potential for calculating programs by optimization. This applies in particular to specifications written in the form of Galois connections, in which one of the adjoints delivers the optimal solution at target.</p>
<p>The framework encompasses re-factoring of results previously developed by Bird and de Moor for greedy and dynamic programming, in a way which makes them less technically involved and therefore easier to understand and play with.</p>
<p>An accompanying <a href="http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections-principles-and-applications/">technical report</a> is available online.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2010/programming-from-galois-connections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Constructing datatype-generic fully polynomial-time approximation schemes using generalised thinning</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2010/constructing-datatype-generic-fully-polynomial-time-approximation-schemes-using-generalised-thinning/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2010/constructing-datatype-generic-fully-polynomial-time-approximation-schemes-using-generalised-thinning/#comments</comments>
		<pubDate>Fri, 08 Oct 2010 00:22:32 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Publication]]></category>
		<category><![CDATA[Workshop]]></category>
		<category><![CDATA[Approximation]]></category>
		<category><![CDATA[Program Derivation]]></category>
		<category><![CDATA[Thinning Theorem]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=508</guid>
		<description><![CDATA[Shin-Cheng Mu, Yu-Han Lyu, and <a href="http://www.riec.tohoku.ac.jp/~morihata/">Akimasa Morihata</a>. Constructing datatype-generic fully polynomial-time approximation schemes using generalised thinning. In the <i>6th ACM SIGPLAN workshop on Generic programming (WGP 2010)</i>,  pages 97-108, Sep. 2010. [<a href="http://www.iis.sinica.edu.tw/~scm/pub/wgp32x-mu.pdf">PDF</a>]]]></description>
			<content:encoded><![CDATA[<p>Shin-Cheng Mu, Yu-Han Lyu, and <a href="http://www.riec.tohoku.ac.jp/~morihata/">Akimasa Morihata</a>. In the <i>6th ACM SIGPLAN workshop on Generic programming (WGP 2010)</i>,  pages 97-108, Sep. 2010. [<a href="http://www.iis.sinica.edu.tw/~scm/pub/wgp32x-mu.pdf">PDF</a>]</p>
<p>The <em>fully polynomial-time approximation scheme</em> (FPTAS) is a class of approximation algorithms that is able to deliver an approximate solution within any chosen ratio in polynomial time. By generalising Bird and de Moor&#8217;s <em>Thinning Theorem</em> to a property between three orderings, we come up with a datatype-generic strategy for constructing fold-based FPTASs. Greedy, thinning, and approximation algorithms can thus be seen as a series of generalisations. Components needed in constructing an FPTAS are often natural extensions of those in the thinning algorithm. Design of complex FPTASs is thus made easier, and some of the resulting algorithms turn out to be simpler than those in previous works.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2010/constructing-datatype-generic-fully-polynomial-time-approximation-schemes-using-generalised-thinning/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Evaluating Simple Polynomials</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2010/evaluating-simple-polynomials/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2010/evaluating-simple-polynomials/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 16:26:09 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Research Blog]]></category>
		<category><![CDATA[Program Derivation]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=482</guid>
		<description><![CDATA[I had a chance to show the students, in 25 minutes, what functional program calculation is about. The student have just been exposed to functional programming a week ago in a three-hour course, and I have talked to them about <a href="http://www.iis.sinica.edu.tw/~scm/2010/maximum-segment-sum-origin-and-derivation/">maximum segment sum</a> way too many times.]]></description>
			<content:encoded><![CDATA[<p>In the end of <a href="http://flolac.iis.sinica.edu.tw/flolac10/">FLOLAC &#8217;10</a> I had a chance to show the students, in 25 minutes, what functional program calculation is about. The student have just been exposed to functional programming a week ago in a three-hour course, after which they have written some simple programs handling concrete data but may have problem grasping those more abstract concepts like folds. I have talked to them about <a href="http://www.iis.sinica.edu.tw/~scm/2010/maximum-segment-sum-origin-and-derivation/">maximum segment sum</a> way too many times (in the context of imperative program derivation, though), and it is perhaps too complex to cover in 25 minutes. The <a href="http://www.iis.sinica.edu.tw/~scm/2009/determining-list-steepness-in-a-homomorphism/">steep list</a> problem, on the other hand, can be dealt with in 5 minutes. Thus I need another example.</p>
<p>This is what I eventually came up with: given a list of numbers <code>a₀, a₁, a₂ ... a<sub>n</sub></code> and a constant <code>X</code>, compute <code>a₀ + a₁X, + a₂X² + ... + a<sub>n</sub>X<sup>n</sup></code>. In Haskell it can be specified as a one-liner:<br />
<code>
<pre>  poly as = sum (zipWith (×) as (iterate (×X) 1))</pre>
<p></code>One problem of this example is that the specification is already good enough: it is a nice linear time algorithm. To save some multiplications, perhaps, we may try to further simplify it.</p>
<p>It is immediate that <code>poly [] = 0</code>. For the non-empty case, we reason:<br />
<code>
<pre>   poly (a : as)
 =   <span class="comment">{ definition of poly }</span>
   sum (zipWith (×) (a:as) (iterate (×X) 1))
 =   <span class="comment">{ definition of iterate }</span>
   sum (zipWith (×) (a:as) (1 : iterate (×X) X))
 =   <span class="comment">{ definition of zipWith }</span>
   sum (a : zipWith (×) as (iterate (×X) X))
 =   <span class="comment">{ definition of sum }</span>
   a + sum (zipWith (×) as (iterate (×X) X))
</pre>
<p></code>The expression to the right of <code>a +</code> is unfortunately not <code>poly as</code> &#8212; the last argument to <code>iterate</code> is <code>X</code> rather than <code>1</code>. One possibility is to generalise <code>poly</code> to take another argument. For this problem, however, we can do slightly better:<br />
<code>
<pre>   a + sum (zipWith (×) as (iterate (×X) X))
 =   <span class="comment">{ since iterate f (f b) = map f (iterate f b) }</span>
   a + sum (zipWith (×) as (map (×X) (iterate (×X) 1)))
 =   <span class="comment">{ zipWith (⊗) as . map (⊗X) = map (⊗X) . zipWith (⊗) as
          if ⊗ associative }</span>
   a + sum (map (×X) (zipWith (×) as (iterate (×X) 1)))
 =   <span class="comment">{ sum . map (×X) = (×X) . sum }</span>
   a + (sum (zipWith (×) as (iterate (×X) 1))) × X
 =   <span class="comment">{ definition of poly }</span>
   a + (poly as) × X
</pre>
<p></code></p>
<p>We have thus come up with the program<br />
<code>
<pre>  poly [] = 0
  poly (a : as) = a + (poly as) × X
</pre>
<p></code><br />
Besides the definitions of <code>sum</code>, <code>zipWith</code>, <code>iterate</code>, etc, the rules used include:</p>
<ol>
<li><code>map f (iterate f x) = iterate f (f x)</code></li>
<li><code>zipWith (⊗) as . map (⊗X) = map (⊗X) . zipWith (⊗) as</code> if <code>⊗</code> associative</li>
<li><code>sum . map (×X) = (×X) . sum</code>, a special case of <code>foldr ⊕  e . map (⊗X) = (⊗X) . foldr ⊕ e</code> if <code>(a ⊕ b) ⊗ X = (a ⊗ X) ⊕ (b ⊗ X)</code> and <code>e ⊗ X = e</code>.</li>
</ol>
<p>Well, this is not a very convincing example. Ideally I&#8217;d like to have a derivation, like the <a href="http://www.iis.sinica.edu.tw/~scm/2009/determining-list-steepness-in-a-homomorphism/">steep list</a>, where we gain some improvement in complexity by calculation. </p>
<p>What is your favourite example for functional program calculation?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2010/evaluating-simple-polynomials/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Sum of Squares of Differences</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2010/sum-of-squares-of-differences/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2010/sum-of-squares-of-differences/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 15:18:38 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Research Blog]]></category>
		<category><![CDATA[Imperative Programs]]></category>
		<category><![CDATA[Program Derivation]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=467</guid>
		<description><![CDATA[Given an array of integers having at least two elements, compute the sum of squares of the difference between all pairs of elements. It is not hard to quickly write up a <code>O(N²)</code> program using nested loops, which, I have to confess, is what I would do before reading Kaldewaij's book and realised that it is possible to do the task in linear time using one loop.]]></description>
			<content:encoded><![CDATA[<p>In the final exam of the <a href="http://flolac.iis.sinica.edu.tw/flolac10/doku.php?id=prog">Program Construction</a> course in <a href="http://flolac.iis.sinica.edu.tw/flolac10/">FLOLAC &#8217;10</a>, I gave the students this problem (from <a href="http://www.amazon.com/Programming-Derivation-Algorithms-Prentice-Hall-International/dp/0132041081">Kaldewaij&#8217;s book</a>):<br />
<code>
<pre>|[ con N <span class="comment">{N ≥ 2}</span>; a : array [0..N) of int;
   var r : int;
   S
   <span class="comment">{ r = (Σ i,j : 0 ≤ i &lt; j &lt; N : (a.i - a.j)²) }</span>
]|</pre>
<p></code>In words, given an array of integers having at least two elements, compute the sum of squares of the difference between all pairs of elements. (Following the convention of the <a href="http://en.wikipedia.org/wiki/Guarded_Command_Language">guarded command language</a>, function application is written <code>f.x</code>, and an array is seen as a function from indices to values.)</p>
<p>It is not hard to quickly write up a <code>O(N²)</code> program using nested loops, which, I have to confess, is what I would do before reading Kaldewaij&#8217;s book and realised that it is possible to do the task in linear time using one loop. Unfortunately, not many students managed to come up with this solution, therefore I think it is worth some discussion.</p>
<h3>Quantifiers</h3>
<p>Before we solve the problem, let us review the &#8220;Dutch style&#8221; quantifier syntax and rules. Given a commutative, associative binary operator <code>⊕</code> with unit element <code>e</code>, if we informally denote the (integral) values in the interval <code>[A .. B)</code> by <code>i₀, i₁, i₂ ... i<sub>n</sub></code>, the quantified expression:<br />
<code>
<pre>   (⊕ i : A ≤ i &lt; B : F.i)</pre>
<p></code>informally denotes <code>F.i₀ ⊕ F.i₁ ⊕  F.i₂ ⊕ ... ⊕ F.i<sub>n</sub></code>. More generally, if all values satisfying predicate <code>R</code> can be enlisted <code>i₀, i₁, i₂ ... i<sub>n</sub></code>, the expression<br />
<code>
<pre>   (⊕ i : R.i : F.i)</pre>
<p></code>denotes <code>F.i₀ ⊕ F.i₁ ⊕  F.i₂ ⊕ ... ⊕ F.i<sub>n</sub></code>. We omit the <code>i</code> in <code>R.i</code> and <code>F.i</code> when there can be no confusion. </p>
<p>A more formal characterisation of the quantified expression is given by the following rules:</p>
<ol>
<li><code>(⊕ i : false : F.i) = e</code></li>
<li><code>(⊕ i : i = x : F.i) = F.x</code></li>
<li><code>(⊕ i : R : F) ⊕ (⊕ i : S : F) = (⊕ i : R ∨ S : F) ⊕ (⊕ i : R ∧ S : F)</code></li>
<li><code>(⊕ i : R : F) ⊕ (⊕ i : R : G) = (⊕ : R : F ⊕ G)</code></li>
<li><code>(⊕ i : R.i : (⊕ j : S.j : F.i.j)) = (⊕ j : S.j : (⊕ i : R.i : F.i.j))</code></li>
</ol>
<p>Rules 1 and 3 give rise to a useful rule "split off <code>n</code>": consider <code>i</code> such that <code>0 ≤ i &lt; n + 1</code>. If <code>n > 0</code>, the set of possible values of <code>i</code> can be split into two subsets: <code>0 ≤ i &lt; n</code> and <code>i = n</code>. By rule 3 (reversed) and 1 we get:<br />
<code>
<pre>  (⊕ i : 0 ≤ i &lt; n + 1 : F.i) = (⊕ i : 0 ≤ i &lt; n : F.i) ⊕ F.n</pre>
<p></code></p>
<p>Expressions quantifying more than one variables can be expressed in terms of quantifiers over single variables:<br />
<code>
<pre>   (⊕ i,j : R.i ∧ S.i,j : F.i.j) = (⊕ i : R.i : (⊕ j : S.i.j : F.i.j))</pre>
<p></code>If <code>⊗</code> distributes into <code>⊕</code>, we have an additional property:<br />
<code>
<pre>   x ⊗ (⊕ i : R : F) = (⊗ i : R : x ⊗ F)</pre>
<p></code></p>
<p>As a convention, <code>(+ i : R : F)</code> is often written <code>(Σ i : R : F)</code>.</p>
<h3>Computing the Sum of Squares of Differences</h3>
<p>The first step is to turn the constant <code>N</code> to a variable <code>n</code>. The main worker of the program is going to be a loop, in whose invariant we try to maintain:<br />
<code>
<pre>   P  ≣  r = (Σ i,j : 0 ≤ i &lt; j &lt; n : (a.i - a.j)²)</pre>
<p></code>In the end of the loop we increment <code>n</code>, and the loop terminates when <code>n</code> coincides with <code>N</code>:<br />
<code>
<pre>   <span class="comment">{ Inv: P ∧ 2 ≤ n ≤ N , Bound: N - n}</span>
   do n ≠ N → ... ; n := n + 1 od</pre>
<p></code>We shall then find out how to update <code>r</code> before <code>n := n + 1</code> in a way that preserves <code>P</code>.</p>
<p>Assume that <code>P</code> and <code>2 ≤ n ≤ N</code> holds. To find out how to update <code>s</code>, we substitute <code>n</code> for <code>n + 1</code> in the desired value of <code>r</code>:<br />
<code>
<pre>   (Σ i,j : 0 ≤ i &lt; j &lt; n : (a.i - a.j)²)[n+1 / n]
 = (Σ i,j : 0 ≤ i &lt; j &lt; n + 1 : (a.i - a.j)²)
 =   <span class="comment">{ split off j = n }</span>
   (Σ i,j : 0 ≤ i &lt; j &lt; n : (a.i - a.j)²) +
   (Σ i : 0 ≤ i &lt; n : (a.i - a.n)²)
 =   <span class="comment">{ P }</span>
   r + (Σ i : 0 ≤ i &lt; n : (a.i - a.n)²)
</pre>
<p></code>This is where most people stop the calculation and start constructing a loop computing <code>(Σ i : 0 ≤ i &lt; n : (a.i - a.n)²)</code>. One might later realise, however, that most computations are repeated. Indeed, the expression above can be expanded further:<br />
<code>
<pre>   r + (Σ i : 0 ≤ i &lt; n : (a.i - a.n)²)
 =   <span class="comment">{ (x - y)² = x² - 2xy + y² }</span>
   r + (Σ i : 0 ≤ i &lt; n : a.i² - 2 × a.i × a.n + a.n²)
 =   <span class="comment">{ Rule 4 }</span>
   r + (Σ i : 0 ≤ i &lt; n : a.i²)
     - (Σ i : 0 ≤ i &lt; n : 2 × a.i × a.n)
     + (Σ i : 0 ≤ i &lt; n : a.n²)
 =   <span class="comment">{ a.n is a constant, multiplication distributes into addition }</span>
   r + (Σ i : 0 ≤ i &lt; n : a.i²)
     - 2 × (Σ i : 0 ≤ i &lt; n : a.i) × a.n
     + (Σ i : 0 ≤ i &lt; n : a.n²)
 =   <span class="comment">{ simplifying the last term }</span>
   r + (Σ i : 0 ≤ i &lt; n : a.i²)
     - 2 × (Σ i : 0 ≤ i &lt; n : a.i) × a.n + n × a.n²
</pre>
<p></code>which hints at that we can store the values of <code>(Σ i : 0 ≤ i &lt; n : a.i²)</code> and <code>(Σ i : 0 ≤ i &lt; n : a.i)</code> in two additional variables:<br />
<code>
<pre>  Q₀  ≣  s = (Σ i : 0 ≤ i &lt; n : a.i²)
  Q₁  ≣  t = (Σ i : 0 ≤ i &lt; n : a.i)
</pre>
<p></code>It merely takes some routine calculation to find out how to update <code>s</code> and <code>t</code>. The resulting code is:<br />
<code>
<pre>|[ con N <span class="comment">{N ≥ 2}</span>; a : array [0..N) of int;
   var r, s, t, n : int;

   r, s, t, n := (a.0 - a.1)², a.0² + a.1², a.0 + a.1, 2
   <span class="comment">{ Inv: P ∧ Q₀ ∧ Q₁ ∧ 2 ≤ n ≤ N , Bound: N - n }</span>
 ; do n ≠ N →
      r := r + s - 2 × t × a.n + n × a.n²;
      s := s + a.n²;
      t := t + a.n;
      n := n + 1
   od
   <span class="comment">{ r = (Σ i,j : 0 ≤ i &lt; j &lt; N : (a.i - a.j)²) }</span>
]|</pre>
<p></code></p>
<h3>Another &#8220;One Loop&#8221; Solution</h3>
<p>Among those students who did come up with a program, most of them resorted to a typical two-loop, <code>O(N²)</code> solution. Given that this 9-hour course is, for almost all of them, their first exposure to program derivation, I shall perhaps be happy enough that around 3 to 4 out of 38 students came up with something like the program above.</p>
<p>One student, however, delivered a program I did not expect to see:<br />
<code>
<pre>|[ con N <span class="comment">{N ≥ 2}</span>; a : array [0..N) of int;
   var r, i, j : int;

   r, i, j := 0, 0, 0
   <span class="comment">{ Inv: ... ∧ 0 ≤ i ≤ j ∧ 0 ≤ j ≤ N, Bound: ? }</span>
 ; do j ≠ N →
       if i &lt; j → r := r + (a.i - a.j)²;  i := i + 1
        | i = j → i, j := 0, j + 1
       fi
   od
]|</pre>
<p></code>The program uses only one loop, but is still <code>O(N²)</code> &#8212; on a closer inspection one realises that it is actually simulating the inner loop manually. Still, I&#8217;d be happy if the student could show me a correctness proof, with a correct loop invariant and a bound, since both of them are more complex than what I expected them to learn. Unfortunately, in the answer handed in, the program, the invariant, and the bound all contain some bugs. Anyone wants to give it a try?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2010/sum-of-squares-of-differences/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fully Polynomial-Time Approximation by Thinning</title>
		<link>http://www.iis.sinica.edu.tw/~scm/2010/fptas/</link>
		<comments>http://www.iis.sinica.edu.tw/~scm/2010/fptas/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 10:57:18 +0000</pubDate>
		<dc:creator>Shin</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Approximation]]></category>

		<guid isPermaLink="false">http://www.iis.sinica.edu.tw/~scm/?p=458</guid>
		<description><![CDATA[Code accompanying a forthcoming paper of Yu-Han Lyu, Akimasa Morihata, and me: Constructing Datatype-Generic Fully Polynomial-Time Approximation Schemes Using Generalised Thinning.]]></description>
			<content:encoded><![CDATA[<p><b>Last update: June 23, 2010</b></p>
<p>Code accompanying a forthcoming paper of Yu-Han Lyu, Akimasa Morihata, and me: Constructing Datatype-Generic Fully Polynomial-Time Approximation Schemes Using Generalised Thinning.</p>
<p>The file <a href="http://www.iis.sinica.edu.tw/~scm/sw/2010/fptas.zip">fptas.zip</a> consists of the following Haskell modules:</p>
<ul>
<li><code>KnapsackSpec</code>: specification of the 0-1 knapsack problem.</li>
<li><code>Knapsack</code>: a thinning algorithm solving knapsack (<code>knapsack</code>), and an approximation algorithm (<code>knapsack_apx</code>).</li>
<li><code>KnapsackTest</code>: some QuickCheck properties to test the code.</li>
<li><code>PartTreesSpec</code>: specification of the maximal tree partition problem.</li>
<li><code>PartTrees</code>: a thinning algorithm solving the tree partition problem (<code>mtp</code>), and an approximation algorithm (<code>mtp_apx</code>).</li>
<li><code>PartTreesTest</code>: some QuickCheck properties to test the code.</li>
<li><code>Utilities</code>: some utilities used by <code>PartTreesSpec</code>.</li>
<li><code>Merging</code>: generalised merging and bumping functions for both programs.</li>
</ul>
<p>The problem instances generated by QuickCheck very rapidly get too large in size. The function <code>smallCheck</code> defined in both <code>*Test</code> modules restricts the sizes of instances generated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iis.sinica.edu.tw/~scm/2010/fptas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

