<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.2" -->
<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/"
	>

<channel>
	<title>Rubrication</title>
	<link>http://www.rubrication.net</link>
	<description>Annotations concerning art, science and life.</description>
	<pubDate>Mon, 09 Nov 2009 16:59:53 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.2</generator>
	<language>en</language>
			<item>
		<title>Type Checking and Cyclic Proof</title>
		<link>http://www.rubrication.net/2009/11/09/type-checking-and-cyclic-proof/</link>
		<comments>http://www.rubrication.net/2009/11/09/type-checking-and-cyclic-proof/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 16:19:48 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<category><![CDATA[Logic]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2009/11/09/type-checking-and-cyclic-proof/</guid>
		<description><![CDATA[Standard functional programming languages like Haskell and SML use polymorphic type systems.  These type systems however, are not sound.  What this means is that the type-systems themselves can not be used to prove properties of the software in the sense of &#8220;total correctness&#8221;.   To see that this is true, we can [...]]]></description>
			<content:encoded><![CDATA[<p>Standard functional programming languages like Haskell and SML use polymorphic type systems.  These type systems however, are not sound.  What this means is that the type-systems themselves can not be used to prove properties of the software in the sense of &#8220;total correctness&#8221;.   To see that this is true, we can get a &#8220;proof&#8221; (read program) of inhabitation of any arbitrary type A, by simply using the program:</p>
<p>data Bot {- Look Ma! No constructors! -}<br />
bot :: Bot<br />
bot = bot</p>
<p>Clearly when we say that bot is an inhabitant of Bot, we dont mean that it actually produces a value of type Bot, since there aren&#8217;t any as Bot has no constructors!  We can easily use this type of proof to prove something like A &and; ¬A which leads to a pretty degenerate logic.  However, the type system is still *useful* in the sense that if the program ever *does* terminate, it&#8217;s sure to do so with the appropriate type.  This means we can get the full class of Turing complete programs, a very useful benefit. </p>
<p>In Constructive Type Theory, we need to keep stronger guarantees.  For programming languages such as Coq, we use syntactic restrictions to ensure that programs terminate (or coterminate).  This however has the annoying feature that a lot of programs which are obviously (co)terminating will be rejected simply because of syntax.  </p>
<p><a href="http://www.doc.ic.ac.uk/~jbrother/slides/imperial_04_08.pdf">Cyclic proofs</a> give a method of describing inductive or coinductive proofs without requiring that we demonstrate the fact that our term (co)terminates <em>up front</em>.   We can defer the proof until later.  The huge advantage to this is that we can use ideas from supercompilation, as a form of proof normalisation and then show that the syntactic termination criteria are satisfied for the resulting transformed proof, rather than for the original.</p>
<p>As an example, take the following program (with the usual list, cons notation from Haskell): </p>
<pre>
 codata CoNat = Z | S CoNat
 data List = [] | (:) CoNat List

 plus :: CoNat -> CoNat
 plus Z y = y
 plus (S x) y = S (plus x y)

 sum :: List -> CoNat
 sum [] = Z
 sum (x:xs) = plus x (sum xs)
</pre>
<p>Now, we can associate with this the following (infered) pre-proof type tree: </p>
<p><img src="http://rubrication.net/file-uploads/example1.png" alt="Pre-proof of sum" /></p>
<p>Now, we can use the usual super-compilation manipulations on this type tree, including beta-reduction, etc. to arrive at this new tree: </p>
<p><img src="http://rubrication.net/file-uploads/example2.png" alt="Proof of sum" /></p>
<p>This is actually a proof, rather than a pre-proof as can be verified syntactically.  It satisfies the guardedness condition of coinduction, and the structural recursion condition for induction. </p>
<p>From the proof above, we can derive the following program, which is syntactically sound.</p>
<pre>
 sum [] = Z
 sum (Z:xs) = sum xs
 sum (S:xs) = S(f x xs)

 f Z xs = sum xs
 f (S x) xs = S(f x xs)
</pre>
<p>This process is basically an extended form of cut-elimination where we can extend the applicability of cut-elimination since we don&#8217;t directly use induction rules, but instead we use cycles in the proof.  We can then work with transformations over a larger class of things which are similar to normalisation.  </p>
<p>There are a lot of advantages to this approach.  In the first program our function &#8217;sum&#8217; did not meet the guardedness condition, which means it would not be admissible in Coq, despite being perfectly correct (as it is in fact productive).  Using pre-proofs we can defer proof, which gives us better compositionality.  We can even use higher order functions which are not in general correct, on particular functions to derive programs which are totally correct.</p>
<p>In addition, we can decide only to show total correctness for regions of a program, rather than the entire program.  We could decide that only certain regions require total correctness, and freely mix total correctness with partial correctness. </p>
<p>There is still a ton of work to be done in this area.  It would be nice to know what proof transformation rules coupled with which algorithms can solve various classes of problems.  <a href="http://portal.acm.org/citation.cfm?id=1380269">Kamendantskaya</a> has a very interesting class of productive functions which, I believe, could be found using a particular proof transformation algorithm.  I&#8217;d like to have this algorithm and a proof that it works.  In addition, I&#8217;d like to have more examples where this can be used to enhance compositionality (I&#8217;m thinking of filter functions in particular, where this might come in handy). </p>
<p>Sorry if this blog post is a bit &#8220;whirl-wind&#8221;.  I intend to lay out the entire theory in a slower and better motivated way later.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2009/11/09/type-checking-and-cyclic-proof/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The Co-Natural Numbers in Haskell and Coq</title>
		<link>http://www.rubrication.net/2008/02/27/the-co-natural-numbers/</link>
		<comments>http://www.rubrication.net/2008/02/27/the-co-natural-numbers/#comments</comments>
		<pubDate>Wed, 27 Feb 2008 21:48:31 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<category><![CDATA[Logic]]></category>

		<category><![CDATA[Maths]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2008/02/27/the-co-natural-numbers/</guid>
		<description><![CDATA[I was playing around with the Peano numerals in Haskell (as I often do), because I remember briefly reading about a generalisation of exponentiation in a paper once when I didn&#8217;t have time to read it.  I decided I&#8217;d quickly look at it again now that I was in a mood to procrastinate. 
&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with the Peano numerals in Haskell (as I often do), because I remember briefly reading about a generalisation of exponentiation in a paper once when I didn&#8217;t have time to read it.  I decided I&#8217;d quickly look at it again now that I was in a mood to procrastinate. </p>
<pre><font color=Cyan>&gt;</font> <font color=Green><u>data</u></font> Nat <font color=Red>=</font> Z <font color=Red>|</font> S Nat <font color=Green><u>deriving</u></font> Show
</pre>
<p>This data type is usually identified with the peano numerals.  In fact as we will see, in haskell it isn&#8217;t quite the natural numbers.  We take Z to mean 0 and take (S<sup>n</sup> Z) or (S (S (S &#8230; Z))) n times, to mean n.  It&#8217;s basically a unary number system where the length of the string gives us the number.</p>
<p>It is pretty straightforward to write the basic arithmetic operations on the peano numerals.</p>
<pre><font color=Cyan>&gt;</font> add x Z <font color=Red>=</font> x
<font color=Cyan>&gt;</font> add x <font color=Cyan>(</font>S y<font color=Cyan>)</font> <font color=Red>=</font> S <font color=Cyan>(</font>add x y<font color=Cyan>)</font>
</pre>
<pre><font color=Cyan>&gt;</font> mult x Z <font color=Red>=</font> Z
<font color=Cyan>&gt;</font> mult x <font color=Cyan>(</font>S y<font color=Cyan>)</font> <font color=Red>=</font> add x <font color=Cyan>(</font>mult x y<font color=Cyan>)</font>
</pre>
<pre><font color=Cyan>&gt;</font> expt x Z <font color=Red>=</font> <font color=Cyan>(</font>S Z<font color=Cyan>)</font>
<font color=Cyan>&gt;</font> expt x <font color=Cyan>(</font>S y<font color=Cyan>)</font> <font color=Red>=</font> mult x <font color=Cyan>(</font>expt x y<font color=Cyan>)</font>
</pre>
<p>Here we can see an extension of this series fairly easily.  The only real question we might have is what to do with the base case.  It turns out that (S Z) or 1 is a good choice.</p>
<pre><font color=Cyan>&gt;</font> exptexpt x Z <font color=Red>=</font> <font color=Cyan>(</font>S Z<font color=Cyan>)</font>
<font color=Cyan>&gt;</font> exptexpt x <font color=Cyan>(</font>S y<font color=Cyan>)</font> <font color=Red>=</font> expt x <font color=Cyan>(</font>exptexpt x y<font color=Cyan>)</font>
</pre>
<p>Playing with exptexpt got me thinking about the fact that I wasn&#8217;t dealing with natural numbers and I was curious what I could prove about them.  In order to see that we don&#8217;t actually have the natural numbers we can define the following:</p>
<pre><font color=Cyan>&gt;</font> inf <font color=Red>::</font> Nat
<font color=Cyan>&gt;</font> inf <font color=Red>=</font> S <font color=Cyan>(</font>inf<font color=Cyan>)</font>
</pre>
<p>This element is clearly not a natural number since it is not a valid recursive equation in the sense that there is no decreasing quantity.  It is however a valid <b>corecursive</b> equation.  It is always <b>productive</b> in the sense that it always has it&#8217;s recursive reference inside of a constructor.  We will always be able to &#8220;peel&#8221; something away from this function in order to reason about it. This will become obvious when we start looking at equational reasoning with infinity. </p>
<p>So this leads us to the question: what does inf+x equal?  I&#8217;ll prove it in pseudo-Coq.  Let us make the following conjecture:</p>
<p>&forall; x, inf + x = inf</p>
<pre>
Theorem : &forall; x, inf + x = inf.
  By coinduction:

  case x = 0:
    1a) inf + 0 = inf
    2a) inf = inf
    * true by the reflexive property of =
  case x = S x'
    1b) inf + S x' = inf
    2b) S (inf + x') = inf
    3b) S (inf + x') = S inf
    4b) inf + x' = inf
    * true as this is the coinductive hypothesis!
Qed.
</pre>
<p>Now the equality that we are using here is actually not term based equality.  It is a coinductive type of equality known as bisimulation.  It also must follow the rule that we can never use recursion unless we are inside a constructor for the type of the function we are using.  The recursion is the coinductive hypothesis.  The constructor prior to the use of the coinductive hypothesis is from the definition of bisimulation.  Namely: </p>
<p>&forall; x y, x = y &rarr; S x = S y.</p>
<p>The full definition in Coq of the bisimulation which we denote above as &#8220;=&#8221; and below as &#8220;CoEq&#8221; is: </p>
<pre>
CoInductive CoEq : CoNat -> CoNat -> Prop :=
| coeq_base : forall x, CoEq Z Z
| coeq_next : forall x y, CoEq x y -&gt; CoEq (S x) (S y).
</pre>
<p>The constructor coeq_next, which is used between step 3b and 4b above ensures that we satisfy our <b>guardedness</b>, or <b>productivity</b> condition and can safely &#8220;call&#8221; the coinductive hypothesis.  What do I mean &#8220;call&#8221; and how is the &#8220;constructor&#8221; being used?  We can see exactly by printing out the term in Coq that proves inhabitation of the type for our proposition.</p>
<pre>
add_x_inf =
cofix add_x_inf (x : CoNat) : x + inf ~= inf :=
  eq_ind_r (fun c : CoNat => x + c ~= c)
    (eq_ind_r (fun c : CoNat => c ~= S inf)
       (coeq_next (x + inf) inf (add_x_inf x)) (add_x_s x inf))
    (decomp_eql inf)
     : forall x : CoNat, x + inf ~= inf
</pre>
<p>Here we see in gory detail a corecursive function that allows us to show this type is inhabited along with the corecursive call shown embedded in the constructor coeq_next.  Sorry if it isn&#8217;t very readable, it was constructed automagically from the proof script. </p>
<p>To see how this is all done in detail, check out the <a href="http://www.rubrication.net/file-uploads/plus.v">Coq proof script for the co-naturals</a>.  This might be interesting to those of you who want to see how to use coinductive reasoning on simple examples and how setoids work in Coq.  You&#8217;ll notice that the reasoning is slightly more cumbersome then what I&#8217;ve used here.  I think this mostly comes down to the &#8220;cofix&#8221; tactic being unwieldy in coq, and making automation a hassle.  I&#8217;m going to think about ways to fix this since it really is unnecessarily inconvenient. </p>
<p>Here are some helper functions which convert from positive integers into our representation so you can play with the code more easily.</p>
<pre><font color=Cyan>&gt;</font> to <font color=Magenta>0</font> <font color=Red>=</font> Z
<font color=Cyan>&gt;</font> to <font color=Cyan>(</font>n<font color=Cyan>+</font><font color=Magenta>1</font><font color=Cyan>)</font> <font color=Red>=</font> <font color=Cyan>(</font>S <font color=Cyan>(</font>to n<font color=Cyan>)</font><font color=Cyan>)</font>
</pre>
<pre><font color=Cyan>&gt;</font> from Z <font color=Red>=</font> <font color=Magenta>0</font>
<font color=Cyan>&gt;</font> from <font color=Cyan>(</font>S x<font color=Cyan>)</font> <font color=Red>=</font> <font color=Magenta>1</font><font color=Cyan>+</font><font color=Cyan>(</font>from x<font color=Cyan>)</font>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2008/02/27/the-co-natural-numbers/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Verifying the Monad Laws with Supercompilation</title>
		<link>http://www.rubrication.net/2008/02/09/verifying-the-monad-laws-with-supercompilation/</link>
		<comments>http://www.rubrication.net/2008/02/09/verifying-the-monad-laws-with-supercompilation/#comments</comments>
		<pubDate>Sat, 09 Feb 2008 14:13:42 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<category><![CDATA[Logic]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2008/02/09/verifying-the-monad-laws-with-supercompilation/</guid>
		<description><![CDATA[A while ago I wrote a post about how one can use coq to make a proper monad module.  I was just thinking today that it would be nice to have a tool for haskell that would allow one to write down conjectures and discharge them automatically with a theorem prover.  Supercompilation makes [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I wrote a post about how one can use coq to make a proper monad module.  I was just thinking today that it would be nice to have a tool for haskell that would allow one to write down conjectures and discharge them automatically with a theorem prover.  Supercompilation makes a nice clean theorem prover for haskell since one could express the equations of interest in haskell itself.   Below is an example of the list monad, and then the 3 monad laws written as conj1,conj2 and conj3.  I prove the first law by manual supercompilation.  The next two are left as an exercise for the interested reader.</p>
<pre>
equal xs ys = case xs of
                [] -> case ys of
                        [] -> True
                        _ -> False
                (x:xs') -> case ys of
                             [] -> False
                             (y:ys') -> case (eq x y) of
                                          False -> False
                                          True ->  equal xs' ys'

bind [] f = []
bind (h:t) f = (f h)++(bind t f)

ret a = [a]

conj1 a f = equal (bind (ret a) f) (f a)
conj2 m = equal (bind m (\a -> ret a)) m
conj3 m f g = equal (bind (bind m f) g) (bind m (\x -> (bind (f x) g)))
</pre>
<p>In order to define equality on lists we had to make reference to a different equality predicate on the elements of the list.  We will make the assumption that this equality is decidable and supercompilation can prove the reflexive property for this equality predicate, that is &#8220;eq x x = True&#8221; will be taken as an assumption.  It is somewhat hard to imagine a case where supercompilation would have a hard time with this because of the case substitution rule.</p>
<p>Now we take conj1 and attempt to prove it by semantics preserving transformations of the source code <a href="#ref1">[1]</a>.  I&#8217;ve been brutally explicit in the steps used so that people who are interested can see exactly how to do these sorts of things themselves.  I&#8217;ve found that program transformation techniques can be extremely useful in reasoning about code.  Of course, it helps to assume that all functions are <a href="http://en.wikipedia.org/wiki/Total_function">total</a>, and I&#8217;ll be doing just that.  I use the notation M[x:=y] to mean the substitution of y for x in M.  Aside from that everything is just Haskell.</p>
<pre>
conj1 a f = equal (bind (ret a) f) (f a)

{- unfold equal -}
conj1 a f = case (bind (ret a) f) of
              [] -> case (f a) of
                      [] -> True
                      _ -> False
              (x:xs') -> case (f a) of
                           [] -> False
                           (y:ys') -> case eq x y of
                                        False -> False
                                        True -> equal xs' ys'

{- unfold bind -}
conj1 a f = case (case (ret a) of
                    [] -> []
                    (z:zs) -> (f h)++(bind zs f))
              [] -> case (f a) of
                      [] -> True
                      _ -> False
              (x:xs') -> case (f a) of
                           [] -> False
                           (y:ys') -> case eq x y of
                                        False -> False
                                        True -> equal xs' ys'

{- case distribution -}
conj1 a f = case (ret a) of
              [] -> case (f a) of
                      [] -> True
                      _ -> False
              (z:zs) -> case ((f h)++(bind zs f)) of
                          [] -> case (f a) of
                                  [] -> True
                                  _ -> False
                          (x:xs') -> case (f a) of
                                       [] -> False
                                       (y:ys') -> case eq x y of
                                                    False -> False
                                                    True -> equal xs' ys'

{- unfold ret -}
conj1 a f = case [a] of
              [] -> case (f a) of
                      [] -> True
                      _ -> False
              (z:zs) -> case ((f h)++(bind zs f)) of
                          [] -> case (f a) of
                                  [] -> True
                                  _ -> False
                          (x:xs') -> case (f a) of
                                       [] -> False
                                       (y:ys') -> case eq x y of
                                                    False -> False
                                                    True -> equal xs' ys'

{- case selection -}
conj1 a f = (case ((f z)++(bind zs f)) of
                      [] -> case (f a) of
                              [] -> True
                              _ -> False
                      (x:xs') -> case (f a) of
                                   [] -> False
                                   (y:ys') -> case eq x y of
                                                False -> False
                                                True -> equal xs' ys')
                                     [z := a,  zs := []]

{- substitution -}
conj1 a f = case ((f a)++(bind [] f)) of
              [] -> case (f a) of
                      [] -> True
                      _ -> False
              (x:xs') -> case (f a) of
                           [] -> False
                           (y:ys') -> case eq x y of
                                        False -> False
                                        True -> equal xs' ys'

{- unfold bind  -}
conj1 a f = case (case (f a) of
                    [] -> []
                    (z:zs') -> z:(zs'++[])) of
              [] -> case (f a) of
                      [] -> True
                      _ -> False
              (x:xs') -> case (f a) of
                           [] -> False
                           (y:ys') -> case eq x y of
                                        False -> False
                                        True -> equal xs' ys' 

{- case selection, substitution -}
conj1 a f = case (f a) of
              [] -> True
              (z:zs') -> case eq z z of
                           False -> False
                           True -> equal (zs'++[]) zs'

{- Assumption: eq z z = True -}
 conj1 a f = case (f a) of
              [] -> True
              (z:zs') -> equal (zs'++[]) zs'

{- unfold of equal and ++ -}
conj1 a f = case (f a) of
              [] -> True
              (z:zs') -> case (case zs' of
                                 [] -> []
                                 (w:ws) -> w:(ws++[]) of
                           [] -> case zs' of
                                   [] -> True
                                   (y:ys) -> False
                           (x:xs) -> case zs' of
                                       [] -> False
                                       (y:ys) -> case (eq x y) of
                                                   False -> False
                                                   True -> equal xs ys

{- case selection -}
conj1 a f = case (f a) of
              [] -> True
              (z:zs') -> case zs' of
                           [] -> True
                           (w:ws) -> case (eq w w) of
                                       False -> False
                                       True -> equal (ws++[]) ws

{- Assumption: eq w w = True -}
conj1 a f = case (f a) of
              [] -> True
              (z:zs') -> case zs' of
                           [] -> True
                           (w:ws) -> equal (ws++[]) ws

{- fold, (we encountered a repeated instance of 'equal (ws++[]) ws') -}
conj1 a f = case (f a) of
              [] -> True
              (z:zs') -> let g = \ xs ->
                                 case xs of
                                   [] -> True
                                   (y:ys') -> g ys'
                         in g zs'
</pre>
<p>Now we have a function that can only return true, regardless of the value of (f a) and assuming that f is total, we can replace this term with True.  The proof of this is simply by induction on (f a), but the principle can be built into a checker and is the principle used in the Poitín <a href="#ref3">[3]</a> theorem prover.  </p>
<p>Something along these lines would be very light-weight in comparison to using a full theorem prover and could just issue a warning if some laws couldn&#8217;t be proved.  The proof of this in Coq is actually more work and requires lemmas about the list type to be proven.  <s>I did in fact fudge the ((f a)++[]) situation there by replacing with (f a), and I&#8217;m not entirely sure what supercompilation does with it if you leave it in.  I&#8217;ll have to try it later.</s> <b>UPDATE:</b> This is fixed in the code above.   </p>
<p>If we want to prove this result by hand we can also derive it in a much simpler way by not following the supercompilation method verbatim:</p>
<pre>
conj1 a f = equal (bind [a] f) (f a)
conj1 a f = equal (append (f a) (bind [] f)) (f a)
conj1 a f = equal (append (f a) []) (f a)
conj1 a f = equal (f a) (f a)
</pre>
<p>The advantage of the former is of course that it is entirely mechanical.</p>
<p><b>UPDATE:</b> I went ahead and incorporated the definition of append and supercompiled it (by hand) with this definition and it reduces to exactly the same term, so in fact supercompilation, without any special knowledge, is capable of proving the conjecture.  This is a real win over most proof assistants which would require this append lemma to be proved separately, or incorporated into the knowledge base.  For a more visual and more compact depiction of the derivation we can draw a partial process tree with the append function definition included in the derivation.  </p>
<p><img src="http://www.rubrication.net/file-uploads/monad.png" alt="derivation of the first monad law with supercompilation" /></p>
<p>And indeed the second monad law: </p>
<p><img src="http://www.rubrication.net/file-uploads/monad2.png" alt="derivation of the second monad law with supercompilation" /></p>
<p>Is the third monad law for the list monad provable using supercompilation?  I expect it is, but since I don&#8217;t have a supercompiler, and it is a bit of a bear to do by hand, I&#8217;m not sure.</p>
<p>Incidently, there is already a supercompiler being developed for haskell called <a href="http://www-users.cs.york.ac.uk/~ndm/supero/">Supero</a> <a href="#ref2">[2]</a>.  It probably wouldn&#8217;t be too much work to extend this with theorem proving capabilities using ideas from <a href="#ref3">[3]</a>.</p>
<p><a name="ref1">[1]</a> <a href="http://citeseer.ist.psu.edu/burstall77transformation.html">A Transformation System for Developing Recursive Programs</a><br />
<a name="ref2">[2]</a> <a href="http://www-users.cs.york.ac.uk/~ndm/downloads/draft-supero-10_dec_2007.pdf">A Supercompiler for Core Haskell</a><br />
<a name="ref3">[3]</a> <a href="http://linkinghub.elsevier.com/retrieve/pii/S1571066106001149">Poitın: Distilling Theorems From Conjectures</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2008/02/09/verifying-the-monad-laws-with-supercompilation/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Proof by Program Transformation</title>
		<link>http://www.rubrication.net/2008/01/26/proof-by-program-transformation/</link>
		<comments>http://www.rubrication.net/2008/01/26/proof-by-program-transformation/#comments</comments>
		<pubDate>Sat, 26 Jan 2008 15:22:22 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2008/01/26/proof-by-program-transformation/</guid>
		<description><![CDATA[Program transformation is a sort of meta-compilation where the source and target languages are the same.  In this sense it can be seen as an automorphism on the set of programs in a language.
As was pointed out by Turchin, it is sometimes possible to prove properties of programs simply by performing a program transformation. [...]]]></description>
			<content:encoded><![CDATA[<p>Program transformation is a sort of meta-compilation where the source and target languages are the same.  In this sense it can be seen as an automorphism on the set of programs in a language.</p>
<p>As was pointed out by Turchin, it is sometimes possible to prove properties of programs simply by performing a program transformation.  Basically a program, and a program which verifies it&#8217;s behaviour (a predicate) can be replaced with a truth value if the program transformation is sufficiently powerful.  An obvious example of course, which can be calculated using partial evaluation would be something like (max (&lt; 3) (1::2::1::nil)).  In fact very complex properties can be proved automatically by Distillation, a particularly powerful program transformation system. </p>
<p>In my research I&#8217;ve been working with the &mu;-Calculus, which is a type of temporal logic that is very powerful (LTL, CTL, CTL* can all be embedded in the &mu;-Calculus) and good for describing reactive systems.  It uses a notion of least and greatest fixed-points in order to describe temporal properties.  This lead me to consider infinite proofs, bi-simulation and co-induction in the context of distillation.   </p>
<p>I was reading a paper [1], which lead me to wonder if Distillation couldn&#8217;t be used as a means of determining if two programs bi-simulate in a very simple way.  Distillation can be viewed as a relation between programs, such that a program <em>a</em> and a program <em>b</em> are related by <em>a D b</em> iff <em>a</em> Distils to <em>b</em> (that is <em>b</em> is the result of running the distillation algorithm on <em>b</em>).  If the bi-simulation relation is called <em>~</em> then we have trivially that: </p>
<p>&forall; a b c &isin; PROG. a D c &and; b D c &rarr; a~b</p>
<p>This is obvious since <em>D</em> is semantics preserving, and <em>c</em> must have the same semantics as both <em>a</em> and <em>b</em>.  So this looks a little bit silly at first, what good can this possibly be?  Can we ever expect this to happen?  Well, I was a little bit surprised to find that it does work for simple examples that I tried on paper.  For instance, let us take the following program. </p>
<pre>
iterate f x = x:(iterate f (f x))
map f (h:tl) = (f h):(map f tl)
cofix f = f (cofix f)
</pre>
<pre>
conjecture_1 f x = iterate f (f x)
conjecture_2 f x = map f (iterate f x)
</pre>
<p>We will assume that the &#8220;:&#8221; constructor is for a type of lists with no &#8220;nil&#8221; terminator, that is, we are only dealing with infinite lists.  Supercompilation is strictly less powerful than Distillation, but sufficient for this example, and simpler to do on paper.  We will therefore supercompile the two halves of the conjecture:</p>
<p>&forall; f x. iterate f (f x) ~ map f (iterate f x)</p>
<p>to yield:  </p>
<pre>
conjecture_1 f x = iterate f (f x)
-- unfold iterate
conjecture_1 f x = (f x):(iterate f (f (f x))
-- generalise [iterate f (f x), iterate f (f (f x))] =>
--  iterate f (f x) which is just conjecture_1
conjecture_1 f x = (f x):(conjecture_1 f (f x))
conjecture_1 = cofix ( g f x -> (f x):(g f (f x)))
</pre>
<pre>
conjecture_2 f x = map f (iterate f x)
-- unfold map
conjecture_2 f x = case (iterate f x) of h:tl => (f h):(map f tl)
-- unfold iterate
conjecture_2 f x = case (x:(iterate f (f x)) of h:tl => (f h):(map f tl)
-- case law, [h:=x, tl:=(iterate f (f x))]
conjecture_2 f x = (f x):(map f (iterate f (f x))
-- generalise [map f (iterate f (f x)), map f (iterate f x)] =>
-- map f (iterate f x), which is just conjecture_2
conjecture_2 f x = (f x):(conjecture_2 f (f x))
conjecture_2 = cofix ( g f x -> (f x):(g f (f x)))
</pre>
<p>So we can see that conjecture_1 and conjecture_2 are syntactically identical modulo alpha-conversion.  The cofix was added just so that the function name didn&#8217;t obscure the equality.  In fact we could also go to some De Bruijn representation as well, to get rid of the need for alpha-conversion equivalence, but I think you get the picture.  In addition, it is trivial to verify that this is a valid co-recursive program satisfying the guard condition that the recursive call happens under the constructor of the co-inductive type which is the co-domain of the co-recursive function (look at all those &#8220;co&#8221;s!).</p>
<p>The point is though that we have derived a syntactically identical program, and hence proved bi-simulation, using a completely automated procedure!  </p>
<p>So the obvious question of course is, how often will this work?   The technique relies on finding a canonical form.  For non-recursive (NOREC) programs, we can probably always find a canonical form using supercompilation (the <em>S</em> relation, a subset of <em>D</em>).  That is, I expect that:</p>
<p>&forall; p,q,r,s &isin; NOREC. p D r &and; q D s &rarr; r=s</p>
<p>This is probably obviously true to someone who understands better about normal forms in the lambda calculus, but I haven&#8217;t yet proved it for the language over which distillation is defined. </p>
<p>For recursively defined programs, it can&#8217;t be the case that we can always find a canonical form.  This is the undecidability of equivalence for the lambda calculus.  However, I&#8217;ll stick my neck out and conjecture that it will work for all programs of suitably low complexity (PRIMREC, ELEMENTARY maybe? [3]).  This doesn&#8217;t tell us anything about bi-simulation however, since co-recursive programs don&#8217;t have a complexity.  Is there a <em>co-complexity</em> we could use?  It would be really nice to have some class we could show is definitely canonisable. </p>
<p>And while I&#8217;m on a roll playing fast and loose, I&#8217;ll say that I think that Distillation represents &#8220;the right way&#8221; of going about finding &#8220;proof-net&#8221; like structures for intuitionistic logic.  That is, internal to the distillation algorithm we actually form a graph, and in the case of conjecture_1 and conjecture_2 the graphs are identical.  The internal representation used for distillation then is actually the form in which we remove &#8220;The bureaucracy of syntax&#8221; [2] for some subset of possible proofs. </p>
<p>For further reading on some of these ideas: </p>
<p>[1] <a href="http://citeseer.ist.psu.edu/105244.html">Proof Methods for Corecursive Programs</a><br />
[2] <a href="http://citeseer.ist.psu.edu/702184.html">Down with the bureaucracy of syntax!</a><br />
[3] <a href="http://citeseer.ist.psu.edu/244412.html">The Expressive Power of Higher-order Types or, Life without CONS</a><br />
[4] <a href="http://www.sciencedirect.com/science?_ob=ArticleURL&#038;_udi=B75H1-4DDWHYH-2N&#038;_user=10&#038;_rdoc=1&#038;_fmt=&#038;_orig=search&#038;_sort=d&#038;view=c&#038;_acct=C000050221&#038;_version=1&#038;_urlVersion=0&#038;_userid=10&#038;md5=13709e6972c03e4dc57f15bf36ef3436">Deforestation, program transformation, and cut-elimination</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2008/01/26/proof-by-program-transformation/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The type says everything</title>
		<link>http://www.rubrication.net/2007/04/24/strong-specifications/</link>
		<comments>http://www.rubrication.net/2007/04/24/strong-specifications/#comments</comments>
		<pubDate>Tue, 24 Apr 2007 20:44:55 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<category><![CDATA[Logic]]></category>

		<category><![CDATA[Maths]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2007/04/24/strong-specifications/</guid>
		<description><![CDATA[I&#8217;ve mentioned a number of times that given a sufficiently rich type theory we can use the type to provide a specification for the function, such that the function is correct by construction.  I&#8217;d like to give a simple example of how this works in the Coq proof assistant.
The following code is an illustration [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve mentioned a number of times that given a sufficiently rich type theory we can use the type to provide a specification for the function, such that the function is correct by construction.  I&#8217;d like to give a simple example of how this works in the Coq proof assistant.</p>
<p>The following code is an illustration of how the type theory of Coq allows you to fully specify the behaviour of functions.  <a href="http://lists.canonical.org/pipermail/kragen-tol/2007-February/000847.html">Kragen Sitaker made the comment</a> that there weren&#8217;t too many reasonable interpretations of the function of the type given to the assoc function:</p>
<pre>
A -> list (A * B) -> option B
</pre>
<p>that is, a function taking an element of type A, a list of pairs of A and B, to the possibility of a B (and possible failure).  That got me wondering how hard it would be to tighten the noose so that there was only one way to interpret the type but still possibly many implementations that satisfy the type, all of which will yield the same result.</p>
<p>The following code illustrates that this is indeed possible to do in Coq.</p>
<pre>
Require Import List.
Parameter A : Set.
Parameter B : Set.
Definition assoc_list := list (A * B)%type.
Parameter eq_dec : forall (x:A) (y:A),{x=y}+{x&lt;&gt;y}.

Theorem assoc :
  forall (x:A) (l: assoc_list),
    {y | In (x,y) l} + {forall (y:B), ~In (x,y) l}.
  refine
    (fix assoc (x:A) (l:assoc_list) {struct l}
      : {y | In (x,y) l} + {forall (y:B), ~In (x,y) l}
      := match l
           return {y | In (x,y) l} + {forall (y:B), ~In (x,y) l}
           with
           | nil => inright _ (fun y => (fun p : In (x,y) nil => _))
           | ((x',y)::t) =>
             match eq_dec x x' with
               | left lft => inleft _ (exist _ y _)
               | right rgt => match assoc x t with
                                | inleft (exist y p) => inleft _ (exist _ y _)
                                | inright inrgt => inright _ _
                              end
             end
         end) ; clear assoc ; eauto ; subst. constructor. reflexivity.
  firstorder. intros. intro. inversion H ; clear H. firstorder. congruence.
  apply (inrgt y0). assumption.
Defined.
</pre>
<p>This isn&#8217;t the most beautiful code but what it lacks in beauty of implementation it makes up for in ease of reading.  There are only a couple of lines that you need to understand to be assured that this is in fact the correct implementation.</p>
<pre>
Theorem assoc :
  forall (x:A) (l: assoc_list),
    {y | In (x,y) l} + {forall (y:B), ~In (x,y) l}.
</pre>
<p>This function has a type that takes an &#8220;x&#8221; of type &#8220;A&#8221;, a list of pairs and supplies a value &#8220;y&#8221; of type &#8220;B&#8221; with a proof that it came from a pair in which the x provided occurs *AND* that that pair exists in the list l.  If the function can&#8217;t find a pair from which to supply a y, it must supply a proof that no such pair exists in the list.</p>
<p>First a bit of the notation so you can read this theorem properly </p>
<pre>
{ y | P y }
</pre>
<p>Can be read: &#8220;there exists a y such that the property P holds of y&#8221;.</p>
<p>The notation:</p>
<pre>
A + {B}
</pre>
<p>Means that we must supply an A or a proof of B.</p>
<p>The &#8220;In&#8221; predicate is an inductive predicate which specifies membership in a list and is provided by the Coq library. </p>
<p>With a little practice reading types, we can see that the two lines are correct.  We can then run Coq on this code to check that the proof is correct and we can be assured of the correctness of the implementation WITHOUT EVER READING THE CODE!  This means we have reduced the problem of correctness to two simple lines of completely declarative statements.</p>
<p>This function is more complicated than a normal assoc function because it carries all of these proof terms along with it. However, because of the clever people involved in writing Coq we have actually mixed two different type universes together.  One (called Set) for values and one (called Prop) for proofs.  Coq uses this fact to do something very clever.  The {y|P y} existential type and the A+{B} type are designed such that the &#8220;P y&#8221; proof and the {B} proof disappear when we extract (compile) our code.  As an illustration of this amazing fact look at the following ocaml code which has been automatically extracted from our definition:</p>
<pre>
let rec assoc x = function
  | Nil -> Inright
  | Cons (p, t) ->
      let Pair (x', y) = p in
      (match eq_dec x x' with
         | Left -> Inleft y
         | Right -> assoc x t)
</pre>
<p>Voila!  Not only are the proof terms gone, but this is pretty much the code you probably would have written yourself.  Notice that &#8220;Inright&#8221; is a constructor with no information (other than failure), basically implementing the &#8220;Nothing&#8221; of a Maybe type, and the &#8220;Inleft&#8221; as the &#8220;Just&#8221; of a Maybe type.</p>
<p>We have extracted a provably terminating, well specified, totally correct function that runs in ocaml!  And to top it off we can also compile to Haskell!!</p>
<pre>
assoc :: A -> Assoc_list -> Sumor B
assoc x l =
  case l of
    Nil -> Inright
    Cons p t ->
      (case p of
         Pair x' y ->
           (case eq_dec x x' of
              Left -> Inleft y
              Right -> assoc x t))
</pre>
<p>So it isn&#8217;t as if this isn&#8217;t without some cost.  There is a huge learning curve on Coq and I&#8217;m by no means an expert.  The proofs can be arduous, and although this one only took me a couple of minutes, it took far longer than it would have to implement the function directly in ocaml.  However as I gain experience with Coq, I increasingly believe the approach will scale better than traditional approaches to software design.  </p>
<p>In addition to these caveats there is more than one function that satisfies this type.  Namely there is an assoc which starts returning from the end of the list, instead of the beginning.  We could get rid of this problem by specifying which of the elements should be returned, returning all of them, or restricting formation of assoc&#8217;s such that they are mappings.  The latter is very elegant, but somewhat more involved than what we have done. </p>
<p>Functional programming reduces the difficulty of writing correct software by reducing the ways in which bugs can occur.  However, most functional programming languages are unable to put complex constraints like &#8220;this is a sorted list&#8221; or &#8220;implements an assoc function&#8221; into the language.  When other functions rely on the behaviour all kinds of funny things can happen.</p>
<p>I recently had a nasty non-termination bug in SML because a function *required* that the input list be sorted or the function wouldn&#8217;t terminate.  My sort routine made use of a bogus less-than-equal predicate over a data-type which I had neglected to write properly. This caused hours of very difficult debugging.</p>
<p>I&#8217;m acting on the thesis that I can avoid these problems and I am rewriting a large program in Coq as an experiment.  I&#8217;ll let you know how it goes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2007/04/24/strong-specifications/feed/</wfw:commentRss>
		</item>
		<item>
		<title>We don&#8217;t need no stinking modules!</title>
		<link>http://www.rubrication.net/2007/04/21/we-dont-need-no-stinking-modules/</link>
		<comments>http://www.rubrication.net/2007/04/21/we-dont-need-no-stinking-modules/#comments</comments>
		<pubDate>Sat, 21 Apr 2007 15:35:39 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Uncategorised]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2007/04/21/we-dont-need-no-stinking-modules/</guid>
		<description><![CDATA[In my last post I described how unbelievably cool modules are in Coq.  Well it turns out that there is some disagreement in the community about whether one should even use them!  
Why?  Because the type system in Coq is so powerful we hardly even need them.   In fact with [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post I described how unbelievably cool modules are in Coq.  Well it turns out that there is some disagreement in the community about whether one should even use them!  </p>
<p>Why?  Because the type system in Coq is so powerful we hardly even need them.   In fact with a bit of syntactic sugar for inductively defined types and the generation of constructors we magically get something like first class modules (first-class meaning modules that are actually values that can be passed around to functions etc&#8230;).  Enter the Record. </p>
<pre>
Record MonadBind : Type :=
  { M : forall (A : Type), Type;
    bind : forall (A B : Type), M A -> (A -> M B) -> M B;
    ret : forall (A : Type), A -> M A;
    left_unit : forall (A B : Type) (f : A -> M B) (a : A),
      bind A B (ret A a) f = f a;
    right_unit : forall (A B : Type) (m : M A),
      bind A A m (ret A) = m;
    bind_assoc : forall (A B C : Type) (m : M A) (f : A -> M B) (g : B -> M C) (x : B),
      bind B C (bind A B m f) g = bind A C m (fun x => bind B C (f x) g)
  }.
</pre>
<p>This implements exactly the same strict controls on the instantiation of a Monad that were given with our MONAD signature in the previous post.  Each type can rely on previously defined types in the record giving us the full dependent type system needed to specify a proper monad.  With a little bit of work we can rewrite our module to be an instantiation of a record. </p>
<p><a href="http://www.evil-wire.org/~jacobian/monad_record.v">Look here for the example code</a></p>
<p>How cool is that!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2007/04/21/we-dont-need-no-stinking-modules/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How a real module system should work.</title>
		<link>http://www.rubrication.net/2007/04/21/how-a-real-module-system-should-work/</link>
		<comments>http://www.rubrication.net/2007/04/21/how-a-real-module-system-should-work/#comments</comments>
		<pubDate>Sat, 21 Apr 2007 12:14:53 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<category><![CDATA[Logic]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2007/04/21/how-a-real-module-system-should-work/</guid>
		<description><![CDATA[I&#8217;ve been playing with the Coq proof assistant over the past few days, following closely on some frustrations that I&#8217;ve been having with using SML&#8217;s module system and a bit of toying with type-classes in Haskell.
The gist of the problem is this.  Although you can define type-classes and modules such that external users of [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing with the Coq proof assistant over the past few days, following closely on some frustrations that I&#8217;ve been having with using SML&#8217;s module system and a bit of toying with type-classes in Haskell.</p>
<p>The gist of the problem is this.  Although you can define type-classes and modules such that external users of these modules/type-classes see a uniform interface, consistency is left as an exercise for the implementer.  This is not really acceptable in my view.   When you are writing software, often times *you* are the implementer.  What you really want is for these modules not just to provide a consistent interface to outsiders, but to guarantee the correctness of the implementation!  Isn&#8217;t that the whole point of types?  If we can&#8217;t do that, why are we using types?</p>
<p>Ok, so in Coq I *can* get the properties I&#8217;ve been wanting out of SML&#8217;s module system.  For instance take the following implementation of the Monad signature: </p>
<pre>
Module Type MONAD.
Set Implicit Arguments. 

Parameter M : forall (A : Type), Type.
Parameter bind : forall (A B : Type),
  M A -> (A -> M B) -> M B.
Parameter ret : forall (A : Type),
  A -> M A.

Infix ">>=" := bind (at level 20, left associativity) : monad_scope.
Open Scope monad_scope.

Axiom left_unit : forall (A B : Type) (f : A -> M B) (a : A),
  (ret a) >>= f = f a.
Axiom right_unit : forall (A B : Type) (m : M A),
  m >>= (fun a : A => ret a) = m.
Axiom bind_assoc : forall (A B C : Type) (m : M A) (f : A -> M B) (g : B -> M C) (x : B),
  (m >>= f) >>= g = m >>= (fun x => (f x) >>= g).

End MONAD.
</pre>
<p>This signature describes something much like the monad that is given by the type-class in haskell.  I neglected some stuff like implementing join from bind etc, but we can safely ignore that for now.  The point is that users of the MONAD signature can&#8217;t just fake a monad by supplying an implementation that is nominally the same.  i.e.  In order to implement this MONAD you actually have to have the right signature for &#8220;>>=&#8221; *AND* you have to satisfy the monad laws.  So what does an implementation look like?   Here is an example: </p>
<pre>
Module ListMonad < : MONAD. 

Require Import List.

Set Implicit Arguments.

Definition M := list.

Fixpoint bind (A : Type) (B : Type) (l : M A) (f : A -> M B) {struct l} : M B :=
  match l with
    | nil => nil
    | h::t => (f h)++(bind t f)
  end.

Infix &#8220;>>=&#8221; := bind (at level 20, left associativity) : monad_scope.
Open Scope monad_scope.

Definition ret (A : Type) := fun a : A => a::nil.

Lemma left_unit : forall (A B : Type) (f : A -> M B) (a : A),
 (ret a) >>= f = f a.
Proof.
  intros. simpl. rewrite app_nil_end. reflexivity.
Defined. 

Lemma right_unit : forall (A B : Type) (m : M A),
  m >>= (fun a : A => ret a) = m.
Proof.
  simple induction m.
    simpl. reflexivity.
    intros. simpl.
    cut (bind l (fun a0 : A => ret a0) = l).
      intros. rewrite H0. reflexivity.
      exact H.
Defined. 

Lemma bind_assoc : forall (A B C : Type) (m : M A) (f : A -> M B) (g : B -> M C) (x : B),
  (m >>= f) >>= g = m >>= (fun x => (f x) >>= g).
Proof.
  simple induction m.
    intros. simpl. reflexivity.
    intros. simpl.
    cut (l >>= f >>= g = l >>= (fun x0 : A => f x0 >>= g)).
      intros. rewrite < - H0.
      induction (f a).
        simpl. reflexivity.
        simpl. rewrite IHm0. rewrite app_ass. reflexivity.
      apply H. exact x.
Defined.

End ListMonad.

(* Example *)
Import ListMonad.
Require Import Peano.
Require Import List.

Fixpoint downfrom (n : nat) {struct n} : (list nat) :=
  match n with
    | 0 => n::nil
    | S m => n::(downfrom m)
  end.

Eval compute in (1::2::3::4::nil) >>= downfrom.
  = 1 :: 0 :: 2 :: 1 :: 0 :: 3 :: 2 :: 1 :: 0 :: 4 :: 3 :: 2 :: 1 :: 0 :: nil
     : M nat
</pre>
<p>Ok, That took me about an hour to write.  I&#8217;m not really that good at using Coq, so presumably you could do this more elegantly and in less time.  In any case it would be nice if the proofs could be automated a bit more.  That aside this is a *much* better situation than we have in SML and Haskell.  We have provided a monad that is guaranteed to actually be one!  </p>
<p>I&#8217;m of the growing opinion that software that is forced to meet specifications will end up being less trouble in the end than the current state of free-wheeling wild-west style implementation.  </p>
<p>Coq gives a civilized alternative to the current free-for-all.  Coq can help us make good on the promise that &#8220;well typed programs can&#8217;t go wrong&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2007/04/21/how-a-real-module-system-should-work/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Coq</title>
		<link>http://www.rubrication.net/2007/03/07/coq/</link>
		<comments>http://www.rubrication.net/2007/03/07/coq/#comments</comments>
		<pubDate>Thu, 08 Mar 2007 02:04:57 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2007/03/07/coq/</guid>
		<description><![CDATA[A few months ago I started messing around with The Coq Proof Assistant to figure out what exactly it was, and proceeded to go through the tutorial.
Coq provides a nice interface for doing proofs in an interactive session.  It was a lot of fun but didn&#8217;t seem particularly useful for my research.  
As [...]]]></description>
			<content:encoded><![CDATA[<p>A few months ago I started messing around with <a href="http://coq.inria.fr/">The Coq Proof Assistant</a> to figure out what exactly it was, and proceeded to go through the tutorial.</p>
<p>Coq provides a nice interface for doing proofs in an interactive session.  It was a lot of fun but didn&#8217;t seem particularly useful for my research.  </p>
<p>As I&#8217;ve been playing with the notion of Total Functional Programming, I ended up reading (and actually doing homework) from a book entitled <a href="http://www.cs.kent.ac.uk/people/staff/sjt/TTFP/">&#8220;Type Theory and Functional Programming&#8221;</a>.  This book is excellent by the way!  I highly recommend it to anyone interested in dependent types/proof theory/type theory.  It has a very lucid style and makes a lot of complex notions in type theory very easy to understand.  I even got to find an error in one of the homework examples (now listed in the errata) which is always fun.  </p>
<p>After working through the first 5 chapters I started looking around for a system that would let me apply some of the principles that I had learned. </p>
<p>As it turns out Coq is really a dependently typed functional programming language masquerading as a proof assistant!  I&#8217;ve spent quite a lot of time over the past few weeks writing total functional programs in Coq and proving properties about them.  I&#8217;ve done a bunch of simple things so far, including a proof of correctness for various properties of insertion sort.  I started with merge sort, but stalled when it got too complicated.  I&#8217;m starting to get a feel for using Coq however and large proofs are getting much easier. </p>
<p>In my research I&#8217;ve been working on the implementation of the distillation algorithm (a form of super-compilation) for logic programming.  As it turns out<br />
the distillation algorithm as described by Geoff Hamilton could be a real boon to total functional programming in Coq.  </p>
<p>In Coq all functions and other values are terms that represent witnesses of a proof.  Inhabitation of types is proved exactly by creating a term of the appropriate type.  The &#8220;tactic&#8221; system in Coq is basically a library that helps you build appropriate terms.  Alternately you can supply the proofs directly by writing in the functional programming language that acts as the witness terms of the types.</p>
<p>In order to avoid inconsistency functions are not capable of general recursion or errors or exceptions, as this can immediately lead to proofs of propositions which are not actually inhabited.  A simple example (in psuedo-haskell) would be a function with the following structure.</p>
<p>loop :: int -> arbitrary<br />
loop x = loop x</p>
<p>Clearly &#8220;int -> arbitrary&#8221; is not actually the type of this function.  It doesn&#8217;t terminate and so has type _|_.  Types in languages like ML and haskell aren&#8217;t actually just as they are written, but include the possibilities of non-termination or errors into the type implicitly.  This (arguably) works out alright if you expect to run your program, but if you are trying to prove useful properties in your type system it turns out to be pretty worthless.</p>
<p>Syntactic restrictions are therefor necessary to avoid including non-terminating functions in Coq.  The method chosen is to accept only structurally recursive functions, which can be checked with simple syntactic criterion.  In fact the functions require you to specify *which* argument of a function is structurally recursive.  This works out surprisingly well but can occasionally be a real pain (try working out a unification algorithm without using anything but structural recursion). </p>
<p>In Coq 8.1 they include a way to define functions that include a measure function which provably decreases or to use a well-founded relation (in conjunction with a proof) to show that the function terminates.</p>
<p>Distillation likes to take functions from general recursion to structural tail recursion.  If you could define functions in Coq such that they were then processed by distillation, it would be very useful!</p>
<p>If you haven&#8217;t tried Coq yet, you should.  And if you haven&#8217;t tried total functional programming yet, I suggest trying it in Coq.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2007/03/07/coq/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Protected access using lightweight capabilities</title>
		<link>http://www.rubrication.net/2007/02/28/protected-access-using-lightweight-capabilities/</link>
		<comments>http://www.rubrication.net/2007/02/28/protected-access-using-lightweight-capabilities/#comments</comments>
		<pubDate>Wed, 28 Feb 2007 10:42:01 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2007/02/28/protected-access-using-lightweight-capabilities</guid>
		<description><![CDATA[The following is some SML code that implements the natural numbers using peano arithmetic in the SML type system.  These numbers can be used to protect access to list functions.  I haven&#8217;t yet figured out if addition is possible, but I&#8217;m hoping that it is.  It could be really handy! 

signature SLIST [...]]]></description>
			<content:encoded><![CDATA[<p>The following is some SML code that implements the natural numbers using peano arithmetic in the SML type system.  These numbers can be used to protect access to list functions.  I haven&#8217;t yet figured out if addition is possible, but I&#8217;m hoping that it is.  It could be really handy! </p>
<pre>
signature SLIST =
sig
    type 'a nat
    type Z
    type 'a S
    val S : 'a nat -&gt; 'a S nat
    val P : 'a S nat -&gt; 'a nat
    val Z : unit -&gt; Z nat
    val zerop : 'a nat -&gt; bool
    val toInt : 'a nat -&gt; int 

    type ('elt,'n) slist

    val snil : unit -&gt; ('elt, Z nat) slist
    val scons : 'elt -&gt; ('elt, 'n nat) slist -&gt; ('elt, 'n S nat) slist
    val :+: : 'elt * ('elt, 'n nat) slist -&gt; ('elt, 'n S nat) slist
    val shd : ('elt, 'n S nat) slist -&gt; 'elt
    val stl : ('elt, 'n S nat) slist -&gt; ('elt, 'n nat) slist
    val slen : ('elt, 'n S nat) slist -&gt; int

end

structure SList :&gt; SLIST =
struct
    (* encode integer types *)
    type 'a nat = int
    type Z = unit
    type 'a S = unit
    fun S i = i+1;
    fun P i = i-1;
    fun Z () = 0
    fun zerop 0 = true
      | zerop _ = false
    fun toInt d = d

    type ('elt, 'n) slist = 'elt list * 'n

    fun snil () = ([],0)

    fun scons elt sl =
	let val (l,i) = sl
	in ((elt::l),S i)
	end    

    infixr :+:
    fun x :+: y = scons x y

    fun shd sl =
	let val (h::t,i) = sl
	in h
	end

    fun stl sl  =
	let val (h::t,i) = sl
	in (t,P i)
	end

    fun slen sl =
	let val (_,i) = sl
	in i
	end

end 

open SList
infixr :+:

val mylist = 1 :+: 2 :+: 3 :+: snil();
val the_head = shd mylist;
val the_tail = stl mylist;
val the_next_head = shd the_tail;
(*
This doesn't even compile!
val head_of_nil = shd (snil())
*)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2007/02/28/protected-access-using-lightweight-capabilities/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Automated Deduction and Functional Programming</title>
		<link>http://www.rubrication.net/2007/02/03/automated-deduction-and-functional-programming/</link>
		<comments>http://www.rubrication.net/2007/02/03/automated-deduction-and-functional-programming/#comments</comments>
		<pubDate>Sat, 03 Feb 2007 19:55:47 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Computer Science]]></category>

		<category><![CDATA[Logic]]></category>

		<category><![CDATA[Maths]]></category>

		<guid isPermaLink="false">http://www.rubrication.net/2007/02/03/automated-deduction-and-functional-programming/</guid>
		<description><![CDATA[I just got &#8220;ML for the working programmer&#8221; in the mail a few days ago,
and worked through it at a breakneck pace since receiving it.  It
turns out that a lot of the stuff from the &#8220;Total Functional
Programming&#8221; book is also in this one.  Paulson goes through the use
of structural recursion and extends the [...]]]></description>
			<content:encoded><![CDATA[<p>I just got &#8220;ML for the working programmer&#8221; in the mail a few days ago,<br />
and worked through it at a breakneck pace since receiving it.  It<br />
turns out that a lot of the stuff from the &#8220;Total Functional<br />
Programming&#8221; book is also in this one.  Paulson goes through the use<br />
of structural recursion and extends the results by showing techniques<br />
for proving a large class of programs to be terminating.  Work with<br />
co-algebras and bi-simulation didn&#8217;t quite make it in, except for a<br />
brief mention about co-variant types leading to the possibility of a<br />
type: D := D &rarr; D which is the type of programs in the untyped lambda<br />
calculus, and hence liable to lead one into trouble.</p>
<p>I have to say that having finished the book, this is the single most<br />
interesting programming book that I&#8217;ve read since &#8220;Paradigms of<br />
Artificial Intelligence Programming&#8221; and &#8220;Structure and Interpretation<br />
of Computer Programs&#8221;.  In fact, I would rate this one above the other<br />
two, though I think it might be because of my current interests.  </p>
<p>The conjunction of &#8220;Total Functional Programming&#8221; and &#8220;ML for the<br />
Working Programmer&#8221; have completely changed my world view of automated<br />
deduction.  Interestingly, my advisers work looks even more appealing<br />
from this perspective.</p>
<p>The basic crux of the issue is this.  Given that we restrict ourselves<br />
to total functional programming, as described in the aforementioned<br />
article, we will have the ability to prove theorems directly by<br />
manipulation of the program source.  </p>
<p>My adviser told me about this the first time that I met him.  It at<br />
first seemed like a curiosity.  It has however, blossomed into a<br />
completely different way of thinking about how proofs should be<br />
performed. </p>
<p>I&#8217;ve spent the last few days converting proofs into program source,<br />
which I then manipulate equationally.  I have a few examples of<br />
inductive proofs that can be written quite naturally as structurally<br />
recursive functions.</p>
<pre>
datatype nat = Z | S of nat

fun lt n m =
    case m of
	Z => false
      | (S m') =>
	case n of
	    Z => true
	  | (S n') => lt n' m'

fun divide n d =
    case n of
	Z => (Z,Z)
      | (S n') =>
	let val (q',r') = divide n' d in
	    case lt (S r') d of
		true => (q',S r')
	      | false => (S q',Z)
	end
</pre>
<p>Both of these functions are direct &#8220;extractions&#8221; of a program from a<br />
proofs that I wrote.  The second one is a proof with two existential<br />
variables.  The two existential variables present themselves as return<br />
values.  In the case of &#8220;lt&#8221; it simply computes a truth value.</p>
<p>The datatype nat = Z | S of nat defines natural numbers with the<br />
correspondence Z=0, S(Z)=1, S(S(Z))=2 etc&#8230;</p>
<p>The proof is a proposition that goes like this:</p>
<p>&forall;n,d:nat. d>0 &exist;q,r:nat. n=dq+r &and; 0&le;r&lt;d</p>
<p>You might notice I dropped the restriction on d in the actual source<br />
code.  That can be encoded with an auxiliary function in any case. </p>
<p>The proof proceeds inductively, basically you can turn the divide<br />
function inside out to recover the inductive proof.</p>
<p>The base case is n=0 which gives 0=dq+r which gives r=0 and q=0 (since<br />
d is greater than 0).  The first case is exemplified in the case<br />
structure above.  (Z,Z) = (q,r) the two existential variables are<br />
returned with a valid result for n=0.</p>
<p>The inductive case is this. </p>
<p>n:     &exist;q,r.  n=dq+r     &and; 0&le;r&lt;d<br />
(n+1): &exist;q&#8217;,r&#8217;. n+1=dq&#8217;+r&#8217; &and; 0&le;r&#8217;&lt;d<br />
if(r+1)&lt;d<br />
then n+1=dq+r+1</p>
<p>We see that this gives us that r&#8217;=r+1, q&#8217;=q giving us a solution to r&#8217; and q&#8217; from r and q (and hence solving the n case, gives us some information about n+1)</p>
<p>else n+1 = d(q+1)+r&#8217;</p>
<p>which we can rewrite as: n+1 = d(q+1)+r&#8217; = dq+d+r&#8217;=dq+r+1 so d+r&#8217;=r+1,<br />
but r+1 must be at least d otherwise we wouldn&#8217;t have failed the test<br />
r+1&lt;d, and r&#8217; can be no less than zero, so we must choose r&#8217;=0<br />
this results in (finally!) </p>
<p>n+1 = d(q+1) with r&#8217;=0,q&#8217;=q+1</p>
<p>We have a proof!  For the extracted program you can look at the source<br />
and see that in fact it mirrors the proof directly, short of a few<br />
simplifications done by hand.  Making use of the r,q in the proof of<br />
r&#8217; and q&#8217; is the same as my use of r and q in my proof of the n+1 case.</p>
<p>I&#8217;m looking forward to a deeper understanding of the correspondences<br />
between proofs and programs with my new found capacity to produce actual functional program proofs by extraction manually.  I&#8217;m also<br />
curious to try my hand at generating termination proofs directly, and<br />
also at making a syntax that more directly supports total functional<br />
programming.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubrication.net/2007/02/03/automated-deduction-and-functional-programming/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
