Wednesday, September 14, 2011

Time != Money

Today's xkcd comic depends on a very common, but unjustified economic equation: that time is money. More precisely, I am objecting to the practice of using a person's hourly salary to evaluate the amount of money lost when that person wastes one hour of his time.

Granted, if that person wastes time during working hours, then he costs at least that much to his employer. At least as much, because employers expect employee work to yield returns over and above the cost of their salary; otherwise, it would be economically pointless to have employees.

But why would the employee himself be deemed to lose that money? If he wastes his time during office hours, he gets his hourly salary anyway. If the time wasted is not during office hours, then the opportunity cost of wasting this time is zero: had he done something else with his time, he would not be earning any money either.

Perhaps "time is money" only applies to startup founders, whose startup-related work directly impact their bottom line. But this line of thinking works precisely because founders don't have an hourly salary; rather, their net worth is a function of the worth of the company they own. So it still doesn't make sense to compare time and hourly salary.

That being said, I still think that Time is a very precious resource. I want to enjoy every minute of it; I just don't buy the idea that I'm wasting money doing so.

Saturday, October 09, 2010

Equality is a (useless) transmutation machine

Even since I heard about the Curry-Howard isomorphism, I've been wondering: to which computational principle corresponds equality? and the axiom of choice? and all those other mathematical concepts which would probably be much more intuitive to me in computational form? Unfortunately, there is no Curry-Howard dictionary translating concepts from one domain to the other, much like a French-English dictionary would translate words from one language to the other.

A few of the correspondances are well-known. A proposition corresponds to a type, and the proofs of this proposition correspond to the inhabitants of this type. A theorem using the hypothesis A to prove proposition B corresponds to a function from type A to type B.

A number N corresponds to a type with exactly N inhabitants. The multiplication A × B corresponds to the tuple type (A, B). The addition A + B corresponds to the algebraic type Either A B, whose set of inhabitants is the disjoint union of the inhabitants of A and the inhabitants of B. The exponentiation BA corresponds to the function type A → B. But what is equality?

In Agda, a programming language / theorem prover exploiting the Curry-Howard isomorphism, (propositional) equality is defined as follows.

agda data _≡_ {X} : X → X → Set where agda refl : (x : X) → x ≡ x

I must admit that this doesn't help much. This states that the only valid proof for x ≡ y is refl x, and even then, it only proves that x ≡ x. In other words, the only inhabitants of the type x ≡ y are values of the form refl x, which actually have type x ≡ x.

A more inspiring piece of Agda code is an example showing how to make use of an equality proof.

agda subst : {X : Set} agda → (P : X → Set) agda → (x y : X) agda → x ≡ y agda → P x agda → P y agda subst P .v .v (refl v) p = p

This code takes some arbitrary proposition P(x), say, "x is prime", a proof that x equals y, a proof that P(x) is true, and concludes that P(y) is also true. For example since 7 is prime and 3 + 4 equals 7, it follows that 3 + 4 is also prime. The code does this by pattern-matching on the proof that x ≡ y, obtaining refl v for some value v. Since refl v has both type v ≡ v and type x ≡ y, Agda concludes that x and y are both v. This changes the type of p from P x to P v and the type of the goal from P y to P v, making it possible for subst to return p.

The feat is more impressive if we use counter-factual equalities. If P(x) says that "x is pink", and you have a proof that Leonardo the Flamingo is pink, and also a counter-factual proof that Leonardo the flamingo is "equal" to Bob the Filthy Frog, then you can convince anyone that Bob is pink, thereby gaining him access to all those cool pink-only bars in town. An x ≡ y equality instance is like a machine you can use to transmute x's access cards into access cards for y.

For this reason, it is in the interest of all the cool pink kids that equality instances should be hard to forge.

And equality instance really are hard to forge. refl x has type x ≡ x, remember? The only transmuter you can build is the one which doesn't actually perform any transmutation. Hence my title: equality is a (useless) transmutation machine.


Oh! One last thing. The bird's-eye view of this post is that equality is a transmutation machine because by using subst, equality instances can be used to transmute things. Couldn't it be that using functions other than subst, equality instances could be used to do even more incredible (yet useless) things?

It turns out the answer is no: an equality instance is no stronger than a substitution machine. The proof of this is that from a substituting machine, we can obtain an equality instance, as follows.

agda unsubst : {X : Set} agda → (x y : X) agda → (subst : (P : X → Set) → P x → P y) agda → x ≡ y agda unsubst x y subst = subst (λ – → x ≡ –) (refl x)

We simply use our substitution machine to transmute the trivial equality instance refl x of type x ≡ x into an equality instance of type x ≡ y. Tada! Equality is (as strong as) a transmutation machine.

Friday, September 17, 2010

How to cope with changing requirements

the context

Programming an application is a complicated endeavor. Often, people outside of the field greatly misjudge the amount of work necessary to implement one; either by vastly underestimating the work necessary to build programs similar to the ones they already use, or by vastly overestimating the work necessary to build programs unlike the ones they already use.

A misguided client in the first category might, for example, come to you saying he would like you to build him a program "just like Microsoft Word, except that [such and such]". An equally misguided client in the second category might be manually adding the same country code to a list of phone numbers every day, because his partners are sending him phone numbers of potential clients, he has to post these phone numbers on a website in order to filter out the numbers that are on the do-not-call-list, and the website expects the phone numbers in a slightly different format.

In a way, the second situation is sadder than the first. In the first situation, the programmer will of course explain immediately that Microsoft Word has a lot of hidden features and that single-handedly duplicating the entire application would take forever. But in the second situation, the poor client might continue to manually perform the task for years until a colleague with some programming experience happens to step into his office at the right moment to ask what he's doing.

the problem

This lack of magnitude appreciation causes a lot of problems when comes the time to settle for the price of a commissioned application. Ideally, clients would know exactly what they want and programmers would know exactly how much work it will take to build what is wanted. In practice, however, clients change their requirements mid-way once they see how their imagined program looks like in real life, or ask for "just one little extra feature" which requires a complete redesign of the application. Programmers could simply stubbornly refuse to deviate from the specification; but alas, not only this isn't a way to treat a paying client, programmers are also notoriously bad at estimating the amount of time a given task will take them.

There exists a number of methodologies (agile, SCRUM...) which aim to solve this problem by involving the client in the process. The basic idea is very simple: if you show intermediate versions of the product to your client, he will change his mind sooner, so you will waste less time working on a version which your client doesn't like.

I must admit that I am not very familiar with these methodologies. My understanding is that they are intended for teams of programmers working together on a single project, so that you would only bother to learn about a methodology if your manager suggests or decides that your team should use it. For an individual programmer working with an individual client, these methodologies look overkill. They sell books explaining these methodologies, and you want to write code, not read books.

the solution

Here's a very simple, no-book-required methodology.

The first time your client comes to see you, let him awkwardly attempt to explain what he wants. Ignore his ill-conceived notion of what the program should look like or how one would use it; you broadly understand what he's trying to accomplish, right? Good. Now, give your client a magazine and tell him that the first version of his software will be ready in an hour. "ONE hour? no way." He'll be shocked, but he'll wait. He won't even notice that you haven't started discussing compensation yet. I bet he didn't expect to see a demo for at least a month.

Now, of course you won't have a working program ready within an hour. But you certainly have the time to create a crude mockup of a program. A few buttons here and there, with the keywords you have heard him rant about written on them. They don't have to do anything when you click on them. The important thing is to have something to show the client as soon as you can.

Once the hour is complete, show the program to the client and tell him that this is version zero, and that many features are still missing. Okay, let's be honest, all of the features are missing, but from the point of view of the client, what you are showing him is already impressive. It's an application built just for him, with buttons labelled with the things he cares about, and it's only been an hour since he met you. I bet he thinks that making the buttons actually do something is "just one little extra feature".

And actually, it is. Let your client play with the mockup interface for a while, then ask him to pick one single feature he would like you to add during the next hour. Help him to pick something of the appropriate complexity. Now, once he understands that the application is going to be built step-by-step, one small feature at a time, and now that he understands how small such a one-step feature actually is, now is the time to discuss pricing.

Ask to be paid a fixed price per version. He's already seen the first version, and you have just told him what the next version will look like, so he can roughly assess how much a single version is worth to him. Negotiate the price as needed. Of course, the client doesn't have to visit every hour for the entire project; after confidence is built, he will probably ask on his own if he could simply give you a list of half a dozen features and come back six versions later. Just make sure not to let him list all the features of his misconceived dream application in one go.

Having the client only pay for running programs also gets rid of one painful situation in which the programmer is making progress on the internals of the application while the client sees an accumulation of bills and no concrete progress, gives up, and decides to cut his losses by abandoning the project. But the point of this payment method is mainly to let the client notice by himself that he can't keep on asking for "just one more little feature" forever, as each time he does so, he pays a little more. Eventually, the client will need to decide that the software is good enough for his needs, and walk away with the last version he paid for.

Wednesday, December 09, 2009

intra-line diff

Introducing linediff, a quick ruby wrapper around diff to highlight changed words instead of changed lines.
#!/usr/bin/ruby
pre, post = $stdin.read.split("\n=======\n")
post[-1..-1] = ""

class String
  def bash
    `bash -c #{inspect.gsub("$", "\\$")}`
  end

  def binspect
    split("\n").map {|s|
      "echo #{s.inspect.gsub("$", "\\$")}"
    }.join(";")
  end

  def to_lines
    gsub("\n", "\\n").gsub(" ", "\n")
  end
  def to_lines!
    gsub!("\n", "\\n")
    gsub!(" ", "\n")
  end

  def to_words
    gsub("\n", " ").gsub("\\n", "\n")
  end
  def to_words!
    gsub!("\n", " ")
    gsub!("\\n", "\n")
  end
end

pre.to_lines!
post.to_lines!
len = pre.length+post.length

both = "diff -U#{len} <(#{pre.binspect}) <(#{post.binspect})".bash
both = both.split("\n")[3..-1]

pre = both.select {|s| s[0..0] != "+"}.join("\n")
post = both.select {|s| s[0..0] != "-"}.join("\n")

pre.gsub!(/^-/, "+")
pre.gsub!(/^ /, "")
post.gsub!(/^ /, "")

pre.to_words!
post.to_words!

puts "#{pre}\n=======\n#{post}"
I use it mostly to handle git conflicts which, in my current setup, show up more often than they should (I repeatedly sync with both a git and an svn repository, which I should not be doing according to git-svn). Here's an example conflict. Can you spot the difference?
<<<<<<< HEAD:thesis.tex
    Once we are done with binary functions, we turn to unary functions, shifting our focus from the aspect weavers to the aspects themselves. Our goal is to help programmers to build aquariums containing the aspects they need, while minimizing the number of proofs needed to achieve this goal. To this end, we provide several generic proofs that create, extend, and translate aquariums with aspects of specific forms. Note, however, that not every pair of functions that commute can be shown to do so using our proofs only, so the programmers are expected to complete our collection with proofs of their own whenever the aspects they need are not of the specific forms covered by our theorems.
    \begin{enumerate}
    \item For every associative and commutative binary function, such as those created using our unordered pair strategy, we can create an aquarium of unary functions corresponding to the elements of the algebraic datatype.
    \item Given an aquarium containing a function $f$, the aquarium can be extended with function $f^n$, for any natural number $n$. The function $f^n$ is the function which repeatedly applies, $n$ times, the function $f$. If $f$ is invertible, the theorem extends to negative integers.
=======
    Once we are done with binary functions, we turn to unary functions, shifting our focus from the aspect weavers to the aspects themselves. Our goal is to help programmers to build aquariums containing the aspects they need, while minimizing the number of proofs needed to achieve this goal. To this end, we provide several generic proofs that create, extend, and translate aquariums with aspects of specific forms. Note, however, that not every pair of functions that commute can be shown to do so using our proofs only, so the programmers are expected to complete our collection with proofs of their own whenever the aspects they need are of the specific forms covered by our theorems.
    \begin{enumerate}
    \item For every associative and commutative binary function, such as those created using our unordered pair strategy, we can create an aquarium of unary functions corresponding to the elements of the algebraic datatype.
    \item Given an aquarium containing a function $f$, the aquarium can be extended with function $f^n$, for any natural number $n$. The function $f^n$ is the function which repeatedly applies, $n$ times in total, the function $f$. If $f$ is invertible, the theorem extends to negative integers.
>>>>>>> df2a5b6eb97ded25a34412d6ff946e0c513da6f3:thesis.tex
    \item If $M$ is a functor, then applying $M$ to all the members of an aquarium transforms the aquarium into a new one, while preserving the pairwise commutativity of its elements.
    %\item We show how parametricity \cite{free_theorems} ensures that structure-manipulating aspects cannot interfere with element-manipulating aspects, thereby reducing the programmer's remaining burden of proof.
    \end{enumerate}
When I encounter such a conflict, I select the code between the "<<<<<<< ... >>>>>>>" and type "!linediff" to tell vim to filter the lines through my ruby script.
<<<<<<< HEAD:thesis.tex
Once we are done with binary functions, we turn to unary functions, shifting our focus from the aspect weavers to the aspects themselves. Our goal is to help programmers to build aquariums containing the aspects they need, while minimizing the number of proofs needed to achieve this goal. To this end, we provide several generic proofs that create, extend, and translate aquariums with aspects of specific forms. Note, however, that not every pair of functions that commute can be shown to do so using our proofs only, so the programmers are expected to complete our collection with proofs of their own whenever the aspects they need are not of the specific forms covered by our theorems. \begin{enumerate} \item For every associative and commutative binary function, such as those created using our unordered pair strategy, we can create an aquarium of unary functions corresponding to the elements of the algebraic datatype. \item Given an aquarium containing a function $f$, the aquarium can be extended with function $f^n$, for any natural number $n$. The function $f^n$ is the function which repeatedly applies, $n$ times, the function $f$. If $f$ is invertible, the theorem extends to negative integers. ======= Once we are done with binary functions, we turn to unary functions, shifting our focus from the aspect weavers to the aspects themselves. Our goal is to help programmers to build aquariums containing the aspects they need, while minimizing the number of proofs needed to achieve this goal. To this end, we provide several generic proofs that create, extend, and translate aquariums with aspects of specific forms. Note, however, that not every pair of functions that commute can be shown to do so using our proofs only, so the programmers are expected to complete our collection with proofs of their own whenever the aspects they need are of the specific forms covered by our theorems. \begin{enumerate} \item For every associative and commutative binary function, such as those created using our unordered pair strategy, we can create an aquarium of unary functions corresponding to the elements of the algebraic datatype. \item Given an aquarium containing a function $f$, the aquarium can be extended with function $f^n$, for any natural number $n$. The function $f^n$ is the function which repeatedly applies, $n$ times in total, the function $f$. If $f$ is invertible, the theorem extends to negative integers.
>>>>>>> df2a5b6eb97ded25a34412d6ff946e0c513da6f3:thesis.tex \item If $M$ is a functor, then applying $M$ to all the members of an aquarium transforms the aquarium into a new one, while preserving the pairwise commutativity of its elements. %\item We show how parametricity \cite{free_theorems} ensures that structure-manipulating aspects cannot interfere with element-manipulating aspects, thereby reducing the programmer's remaining burden of proof. \end{enumerate}
Note that my script detects the "=======" separator and diffs between the lines appearing before and after it. It should be trivial to adapt it to examine different files, like the original diff does. Anyway, the result is that the changed words get prefixed with a "+", which I highlight using vim's ":hlsearch" option.
<<<<<<< HEAD:thesis.tex
    Once we are done with binary functions, we turn to unary functions, shifting our focus from the aspect weavers to the aspects themselves. Our goal is to help programmers to build aquariums containing the aspects they need, while minimizing the number of proofs needed to achieve this goal. To this end, we provide several generic proofs that create, extend, and translate aquariums with aspects of specific forms. Note, however, that not every pair of functions that commute can be shown to do so using our proofs only, so the programmers are expected to complete our collection with proofs of their own whenever the aspects they need are +not of the specific forms covered by our theorems.
    \begin{enumerate}
    \item For every associative and commutative binary function, such as those created using our unordered pair strategy, we can create an aquarium of unary functions corresponding to the elements of the algebraic datatype.
    \item Given an aquarium containing a function $f$, the aquarium can be extended with function $f^n$, for any natural number $n$. The function $f^n$ is the function which repeatedly applies, $n$ +times, the function $f$. If $f$ is invertible, the theorem extends to negative integers.
=======
    Once we are done with binary functions, we turn to unary functions, shifting our focus from the aspect weavers to the aspects themselves. Our goal is to help programmers to build aquariums containing the aspects they need, while minimizing the number of proofs needed to achieve this goal. To this end, we provide several generic proofs that create, extend, and translate aquariums with aspects of specific forms. Note, however, that not every pair of functions that commute can be shown to do so using our proofs only, so the programmers are expected to complete our collection with proofs of their own whenever the aspects they need are of the specific forms covered by our theorems.
    \begin{enumerate}
    \item For every associative and commutative binary function, such as those created using our unordered pair strategy, we can create an aquarium of unary functions corresponding to the elements of the algebraic datatype.
    \item Given an aquarium containing a function $f$, the aquarium can be extended with function $f^n$, for any natural number $n$. The function $f^n$ is the function which repeatedly applies, $n$ +times +in +total, the function $f$. If $f$ is invertible, the theorem extends to negative integers.
>>>>>>> df2a5b6eb97ded25a34412d6ff946e0c513da6f3:thesis.tex
    \item If $M$ is a functor, then applying $M$ to all the members of an aquarium transforms the aquarium into a new one, while preserving the pairwise commutativity of its elements.
    %\item We show how parametricity \cite{free_theorems} ensures that structure-manipulating aspects cannot interfere with element-manipulating aspects, thereby reducing the programmer's remaining burden of proof.
    \end{enumerate}
Tada! Now I know which words have changed since my last unfortunate sync-and-fix-conflicts cycle.

Sunday, September 06, 2009

Samuel's Really Straightforward Proof of the Parametricity Result, extended (trivially) to dependent types.

[I'll eventually write a version which begins by explaining free theorems, but for now here's a proof for the cognoscenti]


Consider an agda expression, any typed agda expression whose type is a Set1. Here are two examples, including one using dependent types.

id : {a : Set}
   → a
   → a
id x = x

ff : {a : Set}
   → {s : a → a}
   → (F : a → Set)
   → (f : {x : a}
        → F x
        → F (s x))
   → {x : a}
   → (y : F x)
   → F (s (s x))
ff F f y = f (f y)

It is very straightforward to obtain a term, ff₁, which has the same type except that Set has been upgraded to a Set1. In fact, the expression ff already has the desired type, we just need to change its type annotation.

id₁ : {a : Set1}
    → a
    → a
id₁ x = x

ff₁ : {a : Set1}
    → {s : a → a}
    → (F : a → Set1)
    → (f : {x : a}
         → (F x)
         → (F (s x)))
    → {x : a}
    → (y : (F x))
    → (F (s (s x)))
ff₁ F f y = f (f y)

Now, let's make this change a bit more generic. Instead of fixing Set1, let's use an abstract target, Set#. Now, since agda doesn't know that Set# is a member of the Set hierarchy, the validity of the expression (x : a) does not follow from the fact that (a : Set#), as it would for (a : Set) or (a : Set1). For this reason, it is necessary to introduce the abstract type transformer (value# : Set# -> Set1), which inserts Set# into the type hierarchy.

It is very straightforward to obtain a term, ff#, which has the same type as ff except that Set has been upgraded to a Set# and value# has been inserted at the appropriate places. In fact, the expression ff already has the desired type, we again just need to change its type annotation.

id# : {a : Set#}
    → value# a
    → value# a
id# x = x

ff# : {a : Set#}
    → {s : value# a → value# a}
    → (F : value# a → Set#)
    → (f : {x : value# a}
         → value# (F x)
         → value# (F (s x)))
    → {x : value# a}
    → (y : value# (F x))
    → value# (F (s (s x)))
ff# F f y = f (f y)

And now the punchline is that ff# is precisely the proof of the free theorem for ff, using the following instantiations for Set# and result#.

record Set# : Set1 where
  field
    a  : Set
    a' : Set
    a~ : a → a' → Set

record value# (a# : Set#) : Set where
  open Set# a#
  field
    x  : a
    x' : a'
    x~ : a~ x x'

Even more free theorems can be obtained by using other instantiations. Note that in the usual formulation of the parametricity result, the type of the free theorems are usually given in a much longer, record-free form where each field is expanded into an individual parameter. It is tedious, but straightforward to convert between the two representations.

free-id' : {a : Set}
         → {a' : Set}
         → {a~ : a → a' → Set}
         → {x  : a }
         → {x' : a'}
         → a~ x x'
         → a~ (id x) (id x')
free-id' {a} {a'} {a~} {u} {u'} u~ = value#.x~ r# where
  a# : Set#
  a# = record {a = a; a' = a'; a~ = a~}

  u# : value# a#
  u# = record {x = u; x' = u'; x~ = u~}

  r# : value# a#
  r# = u#

free-ff' : {a : Set}
         → {a' : Set}
         → {a~ : a → a'
               → Set}
         → {s : a → a }
         → {s' : a' → a'}
         → {s~ : ∀ {x x'}
               → a~ x x'
               → a~ (s x) (s' x')}
         → {F : a → Set}
         → {F' : a' → Set}
         → (F~ : ∀ {x x'}
               → a~ x x'
               → F x → F' x'
               → Set)
         → {f : ∀ {x}
              → F x
              → F (s x)}
         → {f' : ∀ {x'}
               → F' x'
               → F' (s' x')}
         → (f~ : ∀ {x x' x~}
               → {y : F x }
               → {y' : F' x'}
               → F~ x~ y y'
               → F~ (s~ x~)
                    (f y) (f' y'))
         → ∀ {u u' u~}
         → {y : F u }
         → {y' : F' u'}
         → F~ u~ y y'
         → F~ (s~ (s~ u~))
              (ff F f y) (ff F' f' y')
free-ff' {a} {a'} {a~}
         {s} {s'} {s~}
         {F} {F'} F~
         {f} {f'} f~
         {u} {u'} {u~}
         {y} {y'} y~
         = value#.x~ r# where
  a# : Set#
  a# = record {a = a; a' = a'; a~ = a~}

  s# : value# a# → value# a#
  s# x# = let open value# x# in record
        { x = s x
        ; x' = s' x'
        ; x~ = s~ x~
        }

  F# : value# a# → Set#
  F# x# = let open value# x# in record
        { a = F x
        ; a' = F' x'
        ; a~ = F~ x~
        }

  f# : {x# : value# a#}
     → value# (F# x#)
     → value# (F# (s# x#))
  f# {x#} y# = let open value# y# in record
             { x = f x
             ; x' = f' x'
             ; x~ = f~ x~
             }

  u# : value# a#
  u# = record {x = u; x' = u'; x~ = u~}

  y# : value# (F# u#)
  y# = record {x = y; x' = y'; x~ = y~}

  r# : value# (F# (s# (s# u#)))
  r# = ff# F# f# y#

Thursday, February 05, 2009

An even more careful fox

Firefox goes to great lengths to preserve the user's work. For the rare cases when it fails, read this.

If I browse for some time, opening a bazillion tabs before the computer crashes, firefox will offer to restore those tabs as soon as I start it again.

If I type some text in a <TEXTAREA/> form before the computer crashes, firefox will restore the text.

But if I type some text in a fancy editor such as WikEd, my changes will be lost. That's because the (HTML representation of the) text I've created was generated by a great many javascript function calls, and firefox doesn't know whether it's safe to simply call those functions again. Thankfully, firefox does remember the resulting (HTML representation of the) text! It's hidden in your profile's sessionstore.bak file.

~/.mozilla/firefox/*.default/sessionstore.bak

The recovery process, however, is a little bit more involved. In the case of WikEd, I searched for the title of the Wiki article I was editing, and found an innerHTML:"..." assignment soon after. That string contained all of the (HTML representation of the) text I had lost, but it was encoded using escaped hexadecimal sequences ("\xE9"), plus other javascript and HTML annoyances. I found that the easiest way to recover the pure ASCII text was to copy the innerHTML string into the following template:

<script>
document.writeln("...");
</script>

Then, I loaded the resulting html file into a separate firefox tab: the hexadecimal sequences were interpreted, and the HTML code was rendered. Copy-pasting the HTML into WikEd lost the HTML formatting but keep the ASCII text, which is exactly what I wanted. My changes were recovered! Thank you, firefox.

Saturday, January 24, 2009

Rant against charitable organizations (and solution)

I happen to be an highly optimistic person. That's a good thing.

Sometimes, my less optimistic friends think the world is a terrible place to live in. Thankfully, they're wrong, so I can cheer them up by pointing out solutions to the problems they perceive. Given this ability, I think I'd make a great volunteer at one of those teen help hotlines. The problem is, none of them wants my help! Well, none that I could find in my area, anyway.

You see, I never donate to charitable organizations. I think it's dumb to give an organization money so that someone else can help people out and get paid for it. I say, cut the middle man! Let me give you a hand instead.

And you know what they replied? "Great, we do have some volunteer positions available. Your task would be to call people and ask them for donations. Interested?"

They really don't want us concerned citizens to help. Like everybody else, they just want our money.


And of course, being the resourceful optimist that I am, I've got a solution to that. And of course, being the enthusiastic developer that I am, my solution involves building a website.

An ordinary charitable organization would use its website to tell you about its plans for solving the problems of the world, and to request your "help" (that is, your money) for implementing that plan. On my hypothetical website, I would ask you about your plan for solving the problems of the world. And I would show you the plans of the other users, so you can contact them and contribute if you think the plan is worth trying.

Most importantly, the plans would be highly detailed. Where ordinary charitable organizations would merely draw a pie chart showing how they allocate your money, our plans would tell you exactly which actions we want to see performed, and why each action contributes to (a sub-goal which contributes to a sub-goal which contributes to) resolving the issue at hand, say, "ending world hunger".

One of the reasons for using such detailed plans is to convince visitors that our plan will actually succeed. I think there is a tendency to assume that, by default, big organizations know what they are doing, and we can't compete with that bias unless we show that we know what we are doing.

And for those of us who don't know what we're doing, we can always ask for the help of our creative contributors. As a project grows, it should become more and more complete, more and more plausible, and attract more and more contributors. If it doesn't, then it probably wasn't a very good idea to begin with.

The other reason for writing highly detailed plans is to keep track of progress. At the most-detailed level, a plan should consist of concrete actions which individuals can perform. That way, resourceful visitors who are convinced by a plan will be able to contribute by performing the concrete action, and ticking it off as completed.


The idea of empowering the community by replacing big organizations with self-organizing teams of volunteers is not new; I've merely translated existing ideas from the world of software to the world of charity. What I'm promoting, it seems, could be called Open Source Charity. (or "Open Plan", perhaps?)

And what this means, is you don't even have to wait for me to implement the aforementioned website. If you have an idea that could change the world, then just use your favourite issue tracking system, and start organizing issues into a concrete plan. Easy enough, right? The world has plenty of good things as it is, like I've claimed.


Well, have fun making the world a better place. Good luck!

Friday, January 09, 2009

well-foundedness, part 2 of 2: code is data. or is it codata?

Whether it is represented as finite strings or as finite trees, code is finite, and thus code is data, not codata. That should settle the question.

haskell code = 2 + 3 * 4 haskell string_data = "2 + 3 * 4" haskell data Exp = Lit Int | Add Exp Exp | Mul Exp Exp haskell tree_data = Add (Lit 2) (Mul (Lit 3) (Lit 4))

Except, of course, that's not really the question I wanted to ask. In my very first post, I warned that manipulating code as raw strings or trees was a bit primitive, and I've since been taught an alternative: higher-order abstract syntax. For the purpose of this post, that basically means I'm representing the code using a function instead of a data-structure.


With data-structures, proofs are usually done using structural induction (see part 1). But when using a function to represent code, what could be its internal structure? What are its substructures?

The clue lies in the exponential notation for function types. But first, remember the familiar multiplicative notation for, well, product types. If (a, b, c) is a value of type A × B × C, then b would be a substructure of type B. That seems reasonable. Now, consider a function λx. f x of type A → B. The exponential notation for this type is BA = B × B × ... × B, with one occurrence of B per inhabitant of A. If these inhabitants are (a0, a1, ...), then an alternate representation of our function could be (f a0, f a1, ...). This expanded form contains exactly the same information as the lambda notation, it's just a lot more verbose, especially when A has infinitely many inhabitants.

Seeing this explicit notation, an immediate conclusion is that for any value a of the appropriate type, the (value corresponding to the) application f a is a substructure of f. Wow! It was totally unexpected for me. That's why I'm writing about it. To share my excitement. But don't get too excited yet: there's a warning coming up.


I have mildly motivated our search for substructures in functions with the relatively exciting perspective of creating a structural induction proof whose decreasing structures include functions. Well, I hope you're not that motivated, because you can't do that. Function application isn't well-founded at all, at least in some languages. Take the identity function, for example. In Haskell, it is possible to apply the identity function to itself. The resulting substructure, obviously, will be the identity function. But that substructure also has the identity function as a substructure, and by continuing to recur in this fashion, we will never reach a base case. The proof will instead go on, forever, in an infinite regress.

Uh? I hope you're surprised! How could structural induction work with all of those other kinds of substructure relations, yet fail with this one? What's so special about functions?

Let's pause to ponder the presumed absurdity of an infinitely-nested structure. Take lists, for example. They are finite because after a finite number of elements, we reach the end of the list. An infinitely-nested list would go on forever, cons after cons, never reaching an end. While this would be absurd in most programming languages, infinite lists are actually commonplace in Haskell... So maybe functions aren't so unique after all!

Functions and infinite lists are examples of codata, and induction is indeed known not to work with those. Expressions of infinite depth do not have a terminating evaluation; the evaluator can't even read the entire input! I hear we're supposed to use "coinduction" instead, but I can't comment on that technique yet. What I can say, however, is that even though Haskell allows data and codata to mix, it's apparently a bad idea, and there are languages with type systems strong enough to prevent it. In these languages, there are two distinct types for lists, but I haven't seen a distinct type for "cofunctions" yet. I suspect that a function must be codata whenever some of its possible return values are.

Well, I bet you've heard enough about well-founded and non-well-founded structures (data and codata) for your entire life. But personally, I think I'm just getting started.

well-foundedness, part 1 of 2: who cares?

If you're like me, you've often heard of well-foundedness, but never really bothered to learn what it really meant nor why it's important. If you're like most people, on the other hand, then you've never even heard the word and you couldn't care less. Well, go ahead, skip this post. You'll be back and eager to learn once you try and fail to read part 2.





...see? I told you you'd be back. Since you're presumably only interested in understanding enough about well-foundedness in order to follow part 2, I might as well use the same example: a little expression language for evaluating numerical expressions such as 2 + 3 * 4.

haskell data Exp = Lit Int | Add Exp Exp | Mul Exp Exp haskell eval :: Exp -> Int haskell eval (Lit n) = n haskell eval (Add e1 e2) = eval e1 + eval e2 haskell eval (Mul e1 e2) = eval e1 * eval e2 haskell eval (Add (Lit 2) (Mul (Lit 3) (Lit 4)))

Since there are no looping constructs in this simple language, it's reasonable to expect evaluation to always terminate. It's possible to prove so using traditional induction, say, on the height of the expression tree. Induction arguments are routine in mathematics, and thus the previous statement is usually all that is needed in order to convince another mathematician that the eval function always terminates; but since today's post is about different kinds of induction, I'll flesh out the proof so you can see the difference.

proof: by (traditional) induction on the height of the expression tree. Base case: if the tree has height one, i.e. if it is a leaf, then the expression is a literal number of the form Lit n and the evaluation terminates immediately by returning n. For the induction step, suppose eval e terminates for all expressions e of height strictly less than n. We wish to show that eval also terminates on expressions of height exactly n. There are two cases: expressions of the form Add e1 e2 and expressions of the form Mul e1 e2. In either case, e1 and e2 are subtrees of the entire expression, and thus have a strictly smaller height. By the induction hypothesis, eval e1 and eval e2 both terminate, and thus the expressions eval e1 + eval e2 and eval e1 * eval e2 also terminate (assuming Haskell's numeric primitives do). ☐

There are other versions of the above argument which are equally valid. For example, instead of the expression depth, we could use the expression size, meaning the number of constructors (Lit, Add and Mul) used to construct the expression.

haskell size :: Exp -> Int haskell size (Lit n) = 1 haskell size (Add e1 e2) = 1 + size e1 + size e2 haskell size (Mul e1 e2) = 1 + size e1 * size e2

This metric is also smaller for e1 and e2 than for Add e1 e2 and Mul e1 e2, so the induction step will succeed.


The two variants I have discussed so far use numbers (depth, size) to argue termination. The idea is that the base case proves the statement to be true when the number is one, and then the induction step can use this fact to prove that the statement is also true when the number is two. This new fact can in turn be used to prove the statement when the number is three, after which we can handle case four, then case five, and so on. In the end, we'll have a proof for all numbers, meaning that expressions of all sizes and depths have a terminating evaluation.

An alternative view of induction is to begin with a statement with a particular number, say five, about which we are actually interested. The induction step gives us a conditional proof of the statement, which depends on the statement to be true for the number four. But the statement is true for the number four, because it's true for three, because it's true for two, because it's true for one. And the statement is true for one because the base case proves so.

This second view is even a bit more "efficient" than the first, because we don't actually need to decrement so slowly. Add (Lit 2) (Mul (Lit 3) (Lit 4)), of size 5, has a terminating evaluation because Lit 2 and Mul (Lit 3) (Lit 4), of sizes 1 and 3, also terminate; the first by the base case, the second because Lit 3 and Lit 4 terminate. The last two expressions had size 1 and are also proved to terminate by the base case. Notice that we managed not to discuss expressions of size 2 and 4 at all.

Using the more efficient version, we see that the proof for n doesn't need to recur on n-1, but can actually use any m as long as m < n. We can generalize further. Even though induction traditionally uses the less-than relation of natural numbers, it is totally possible to find other suitable relations. Structural induction, for instance, says that the expression e1 is less than expression Add e1 e2 because the latter contains e1 as a sub-expression.

This structural less-than is very different from the numerical less-than. For one thing, the numerical less-than is total, meaning that given two numbers, one of the two is going to be smaller than (or equal to) the other. With structures such as Add (Lit 1) (Lit 2) and Mul (Lit 3) (Lit 4), neither is contained within the other, so the structural less-than isn't total. But while our intuitive, everyday notion of ordering seems to require totality, the notion isn't required by the induction principle.

One notion which is required, however, is (you guessed it) well-foundedness. The property basically states that when recurring on smaller and smaller values, we will hit the base case after finitely many steps. This is required: otherwise, the proof could go on and on and on without the sceptics even being convinced.

Speaking of sceptics: are you convinced that well-foundedness is a useful concept now?

Thursday, December 25, 2008

God exists (with probability one)

Bonjour Gab. Joyeux Noël. C'est un jour tout particulier pour toi, alors profites-en.

Tu n'aimes pas quand, à la messe de minuit, les imposteurs envahissent ton église pour prier maladroitement à tes côtés, alors je ne prétendrai pas partager ton enthousiasme. Par contre, je voulais te rappeler que moi aussi je crois en dieu — juste pas en Dieu, avec une majuscule. Tu dois te dire que je dis ça pour te faire plaisir. Qu'à mes amis athéistes, je dis le contraire avec autant de conviction. Eh bien en fait... ouain, ça ressemble pas mal à ça.

Et c'est pourquoi ce post est, en quelque sorte, un cadeau de Noël. Pour toi, je fais l'effort de choisir un camp officiel et de l'afficher clairement. Bon, peut-être pas aussi clairement que si je l'avais mis sur Facebook, mais en tout cas c'est là où on arrive quand on tape mon nom sur Google ces temps-ci.

Le reste du post est mon argument "anthropique" que tu connais déjà. Alors, si tu préfères profiter du reste de la journée pour penser au petit Jésus et profiter de Noël, c'est un moment idéal pour fermer cette fenêtre.

---

The above French comment isn't necessary to understand the following argument. Feel free to disagree violently with my hypotheses or with my reasoning.

The first of these wild hypotheses is that mathematical truths actually exist, in some parallel Platonic world of ideas. My actual belief is stronger: in a twisted interpretation of modal logic, I believe that necessary truths, such as mathematical tautologies, necessarily exist; whereas the facts about our universe are merely ordinarily true, and therefore physical things only happen to exist. I have been led to these unusual beliefs by a convincing argument using the anthropic principle, which I will not repeat here.

Now that we accept the hypothesis, we have to accept a very, very large number of existing things. True statements about numbers. True statements about sets. True statements about true statements. True statements about programs. True statements about programs running games. True statements about a program running an extremely realistic simulation of our physical universe. True statements, one for each instant, describing the entire contents of the simulated universe at that instant. Oh, did I mention that I also assume that our universe is both computable and indistinguishable from a simulation of itself?

At this point I usually picture the statements in the sequence of universe contents to be shown true one after the other, unfolding the story of the universe at the rate at which we feel it happening. But I have come to realize that time is a universe-specific concept, making it implausible to imagine time flowing by in the world of ideas. Because of this, I must admit that I'm not sure how consciousness should enter the picture, but at this point I am at least reasonably sure that (a possibly consciousness-less version of) our universe exists (what a relief!), and even necessarily exists.

An atheist would stop here and point out that since the universe necessarily exists, there is no need to postulate a god powerful enough to bring it into existence. And I totally agree. Nothing so far has argued for or against the existence of a god. Against the lack of evidence, some people (like me!) prefer to assume a god-less model by default, while others prefer to stick to their own favorite meme. But some of us reason one step further.

My next guest in this series of implausible hypotheses is that some humble universe inhabitants are so powerful that they count as gods in their own right. In my book a god is an entity which creates, maintains, and possibly interacts with one or more universe(s). And since I've already assumed that our universe could be nothing more than a simulation, a god could be little more than a programmer with infinite time on his hands. One can certainly imagine a universe similar to ours in which this was true, a universe which would also necessarily exist. In fact, some of us claim that our universe is itself suitable for setting up the kind of infinite computation which running sub-universes require.

With infinite time on his hands, it's not at all a waste for him to run all finite universes, one after the other, until the non-existing end of time. Surprisingly, it's also possible to run all infinite universes, if he interleaves them cleverly. And while you can't assume that god's unsearchable ways will involve enumerating all programs, we've got so many gods in our collection of necessarily existing universes that I'm sure we can find one who likes to do just that.

Running every possibility, god will eventually create a sub-universe looking just like ours and one just like his, in which a sub-god will be running sub-sub-universes including one like ours and one like his, and so on. We end up with infinitely many identical copies of god, and most importantly, infinitely many identical copies of universes indistinguishable from ours.

Let's recapitulate. We have now established the existence of many, many worlds, some of them like ours, some of them different. At the top level are infinitely many of them, all distinct. One of them is indistinguishable from ours. Infinitely many are extremely close to ours, like the many-worlds of quantum mechanics, but not exactly the same. Those top-level worlds exist by virtue of the first hypothesis, the existence of the world of ideas. Again, nothing so far encourages or precludes a pre-top-level god who created that world, so I default to a god-less model. In addition to the single top-level world which is like ours, infinitely many others exist as sub-universes, created by something in a higher-level universe. Those universes do have some sort of god, namely, that thing which created them. It could very well be a machine without a programmer, or a programmer without a machine.

Many-world models are suitable for probabilistic arguments. For example, if a many-world theory postulates a particular distribution of worlds, it should be possible to calculate the conditional probability of an universe having such and such property given that intelligent beings inhabit it. This could be used to make observable predictions about our universe, and test the theory. Today, however, I'm going to be lame and make a non-observable prediction: the conditional probability of an universe being god-less, given that it is indistinguishable from ours, is zero. After all, there is only one such god-less universe, the one at the top level, divided by infinitely many equally probable indistinguishable universes. Hence, god exists with probability one.

Sunday, November 30, 2008

Non-standard inhabitants

The goal of this post is to demonstrate that I'm not crazy. One of my latest discoveries involves a function called "inhabitants", but that's impossible, so says the textbooks, and I can't explain my discovery any further because I crumble under the mathematically rigorous objections. You know, the way researchers whose latest discovery involves a perpetual motion engine tend not to be taken very seriously.

So I took the time to read about those mathematically rigorous objections, and I'm happy to report that my conclusion is that I am not a crackpot. It's just a misunderstanding. A bit as if my perpetual motion engine was supposed to cycle more slowly at every turn, without ever stopping (hence the name) and without producing useful work. It may or may not be an interesting discovery, but it has nothing to do with what people usually call perpetual motion engines.

Now that I'm convinced of my own sanity, the hard part is to convince others. I'll practice with you, foreign and unknown readers, who are probably too far away to cause me trouble if I fail.


First of, I'd like to explain what people usually mean by "inhabitants". The type inhabitation problem is the task of determining, for any given type in a particular programming language, whether there exists an expression in that language which has that type. Such an expression is said to "inhabit" its type. It would be even more useful if an actual inhabitant could be returned as a witness, and that's precisely what Djinn does for Haskell's type system.

Some people have wondered whether Djinn could be extended to enumerate all the inhabitants of that type, instead of just one. Well, no. And here is a diagonalization argument to prove it.


First, it makes things much simpler if we cast everything in terms of integers. Types and expressions can both easily be encoded as integers, for example by interpreting their ascii representations as base 256 numbers. I'll use the notation ⟨x⟩ to denote the integer representing the type or expression x.

Even though our expressions now masquerade as integers, we should still be able to evaluate them.

haskell eval :: Int -> Int -> Int spec ⟨f⟩ `eval` ⟨x⟩ == ⟨f x⟩

The above code is the specification for eval, not its implementation. It is an incomplete specification, because we don't care about the behaviour of eval when it is given integers which don't represent expressions (rendering the left-hand side meaningless) or when these expressions are of incompatible types (rendering the right-hand side meaningless). In what follows, eval should always be used implicitly whenever the code appears to be applying an integer to another.

Next, by contradiction, suppose we did have a version of Djinn which enumerated all of the inhabitants of a type.

haskell inhabitants :: Int -> Int -> Int spec if (p :: T) then ∃i:Int. inhabitants ⟨T⟩ i == ⟨p⟩

Instead of returning a list of all the results, inhabitants takes an extra integer i as a second argument and returns the ith member of its enumeration. If there are less than i members in the enumeration, then we don't care what inhabitants returns.

Again, that's because the specification is incomplete. It is very incomplete. It doesn't even forbid inhabitants from returning expressions with the wrong type in addition to those who do. It only requires inhabitants not to miss any of the expressions which do have the requested type, because that's all I need in order to derive a contradiction. In fact, I only need to find a single type and a single expression of that type which inhabitants misses. The diagonal, for example.

haskell diag :: Int -> Int haskell diag i = 1 + inhabitants ⟨Int -> Int⟩ i i

This time I did not merely give a specification, but an explicit definition.

The function diag has type Int -> Int, so the specification of inhabitants requires that inhabitants Int -> Int i == diag⟩ for some i. Both sides of this equation should evaluate to the same integer, ⟨diag⟩. And thus, the expressions represented by those identical integers should also be the same. In particular, the expressions should behave the same on all inputs, including input i. But on that input, diag made sure to behave differently, by returning a value that is off by one from the left-hand side's value! Thus, inhabitants Int -> Int⟩ must have missed diag, as needed.


Now that we know that implementing inhabitants correctly is impossible, what's wrong with the following attempt?

haskell inhabitants :: Int -> Int -> Int haskell inhabitants _ p = p

Okay, so it's not a very serious attempt, but it does satisfy the specification. Remember how I said that I didn't need to forbid inhabitants from returning too many expressions? Well here I am, returning all expressions, all the time, regardless of the type requested. How could I miss any?

Let's walk through the argument again. There is some diag function which I'm supposed to miss. The specification requires inhabitants Int -> Int i == diag⟩ for some i. And with this implementation, this happens when i is equal to ⟨diag⟩. At this point, diag is supposed to stab us in the back by adding one!

haskell diag i = 1 + inhabitants ⟨Int -> Int⟩ i i haskell diag ⟨diag⟩ = 1 + inhabitants ⟨Int -> Int⟩ ⟨diag⟩ ⟨diag⟩ haskell diag ⟨diag⟩ = 1 + ⟨diag⟩ `eval` ⟨diag⟩ haskell diag i = 1 + diag i haskell diag i = loop

The foolish diag, however, was stabbed by our infiltrated agents first. It turns out that calling inhabitants Int -> Int i caused diag i not to terminate! Adding one to ⊥ has no effect, and diag failed to distinguish its behaviour from inhabitants Int -> Int i, avoiding a contradiction.

What this tells us, is that the original argument implicitly assumed that inhabitants only enumerated terminating expressions. In turn, this tells us that the type inhabitation problem implicitly requires inhabitants to terminate. And with hindsight, it's rather obvious than they should. Otherwise, the type inhabitation problem would be trivial: every single type would be inhabited!

haskell fake_inhabitant :: a haskell fake_inhabitant = haskell let witness = fake_inhabitant haskell in witness

And now, I can finally reveal what it is that makes my perpetual motion engine possible: the inhabitants function involved in my discovery enumerates expressions which, syntactically, have the correct type, but whether the enumerated expressions terminate or not is irrelevant to my discovery. The fact that I won't be able to produce useful work out of it doesn't mean it can't also be a nice theoretical device. But maybe I really should have called it a "perpetually slowing-down engine", to avoid confusion.


update: In other news, it is also impossible for Djinn to exist. But it's only impossible for versions of Djinn which cover strong enough type systems, like Haskell's. From this, I can conclude that Djinn covers a useful fragment of Haskell, and you can conclude that I don't use Djinn very often.

Friday, November 28, 2008

Axes of the lambda cube

Can't see the math behind the greek? For reference, here are the appropriate greek letters for each abstraction mechanism introduced in each axis of the lambda cube. For completeness, lambda abstraction is also included on its own, even though it appears in all axes.

Each cell begins with an example type, followed by an example term of that type. Either the term, the type, or both (...or neither!) will feature a new greek abstraction letter, introducing a variable that can be used on the right of the period.

These new symbols extend the syntax of the calculus, in a way that is made precise in the last lines of the cell. Those lines extend the basic grammar using a functional notation which models variable introductions more precisely than a context-free grammar could.

Even though some cells introduce more than one new abstraction symbol, each cell only introduces one new kind of application. The syntax for application is always just juxtaposition; the syntactic types of the juxtaposed constructs should make it clear which application is meant. The last line of each cell extends the grammar to support this new kind of application, with a bold fragment highlighting what makes the axis unique.

function types
(A → B) →
  A → B

λf:(A → B).
  λx:A. f x


(→) : type → type → type
λ : type → (term → term) → term
(•) : term → term → term

dependent types
(Πx:Nat. P x) →
  Πy:Nat. P y

λf:(Πx:Nat. P x).
  λy:Nat. f y


Π : type → (term → type) → type
(•) : type → term → type

polymorphic types
(∀A. Nat → A) →
  ∀B. Nat → B

λf:(∀A. Nat → A).
  ΛB. λy:Nat. f B y


∀ : (type → type) → type
Λ : (type → term) → term
(•) : term → type → term

parametric types
(A → B → (P : * → * → *) A B) →
  A → B → P A B

λf:(A → B → P A B).
  λx:A. λy:B. f a b


(→) : kind → kind → kind
(•) : ∀⟨type⟩:kind. (type → ⟨type⟩) → type → ⟨type⟩

Thursday, November 27, 2008

Testing Chrome Overlays

Writing a Firefox extension involves writing a so-called "chrome overlay", which is an xml description of the interface changes you wish to make.

I'm in the process of learning how to write overlays. That means I make mistakes. Lots of them. They're completely normal stepping stones in the process of learning, and I'm totally prepared to spend lots of time doing nothing but mistakes. But while I'm doing this, I'd rather not spend lots of time doing non mistake-related tasks. Non-mistakes reduce the number of mistakes I can do in one day, and thus increase the number of days spent learning.

If, in addition, the non mistake-related task is repetitive and impossible to automate, then I'm likely to get angry. I'm really angry against reinstalling in-progress Firefox extensions right now. Or at least I was, before I found a way to avoid doing it.

My solution is to add two new buttons to my bookmarks toolbar: one for the chrome I want to overlay over, and one which applies my overlay over it. Don't click those links, just look at the URLs to understand the trick, and then only if you're also trying to learn overlays. For everybody else, well... just wait a little bit. The extension I'm working on is going to be really interesting.

...if my attention is not caught by something else before I complete it, that is.

Sunday, November 02, 2008

I want to be a knowledge engineer!

The best thing about being a student is that your job is to learn. Except it isn't really a job at all, since I'm the one paying the university, not the other way around.

The sad thing about being a student, is that it cannot last. Once you've done enough learning, you're expected to go out there in the industrial world and use that knowledge. My current plan is to work in the mornings, raising enough money to pay for my classes autonomous learning (I'm a grad student) in the afternoon. I prefer this to filling out grant application forms.

But I've stumbled upon this fiction-sounding job title, "knowledge engineer", which sounds too good to be true. According to that article, a knowledge engineer acts as an intermediate between domain experts and programmers. So the domain expert does the hard job of finding and reading papers and arguing with other experts and performing experiments and keeping up with the latest research. This process apparently turns experts into brains floating in a vat of brains, thereby losing their ability to communicate with the outside world.

Somewhere in this outside world lies a programmer, who is also a domain expert, an expert in program construction. Thus he lives in his own vat, separate from the domain expert's. The programmer vat is equipped with wheels, and it travels from vat to vat trying to simplify the jobs of the other brains. Many of them perform dull and automatable tasks everyday without realizing that a computer could do it for them, freeing them to do more arguing and reading and experimenting. So the programmers offer to write them useful new tools and the experts agree to explain all of the little details which the programmers could need, and the experts blabber on and on and on and the programmers can't take it anymore. I just need to know whether measuring an increased atmospheric pressure leads to predicting a higher or a lower temperature! Who cares about the details of the moving air masses and the process of cloud formation and the reason altitude messes with our measurement?

I do. I mean the knowledge engineer does, I just wish I was a knowledge engineer. When the programmer vat approaches the expert vat, the knowledge engineer's brain jumps from one vat to the other, and begins to ask questions. He does care about the process of cloud formation because he's naturally curious, and maybe it's not going to help with the problem at hand or maybe clouds, pressure and temperature are all intimately linked in some complicated way which the knowledge engineer just can't wait to discover. Then he jumps back into the programmer vat and explains the parts which turned out to matter to the problem at hand, using words which make sense to the programmers, because at the bottom of his heart, he's one of them. The programmer vat is his own travelling home, the one with the cables floating everywhere and the squeaky mouse-like wheels. Domain experts just love the knowledge engineer, because he cares about their stuff, and programmers also love the knowledge engineer, because he talks their language.

Anybody out there who wants to love me?

Wednesday, October 29, 2008

Rant against beamer's shaky animation support (and solution)

I love LaTeX.

I love it because TeX is a programming language, and the other typesetting products aren't. Other that that, it's a horrible language.

For some reason, I don't follow the "separate presentation from contents" dogma. I guess it must be a bit strange coming from a guy who otherwise strongly advocates separation of concerns in all manners of code, but that's the way it is. Micromanaging the look of my LaTeX creations involves lots of anger against the program's not-quite-perfect sense of aesthetics, a few wasted night, and a handful of life-saving low-level TeX macros. Tonight's fight involved the latter.

beamer is an impressive LaTeX mod for creating slides. The output is a PDF document, so you can only generate a sequence of static slides. No animations, no sound. I mention it in case you expected slide programs to provide these ridiculous toys; me, I'm used to text-only slides and box-based ornaments. That's because I was using LaTeX to create my slides way before I knew about beamer, so I improvised with what I thought was possible. beamer, with its colors and rounded boxes and navigation and gradually uncovered slides, sure showed me how much I underestimated the extent of the possible.

Yet with all of its features, there's one thing I used to be able to do (easily?) with LaTeX alone, and which beamer doesn't offer: uncovering by substitution. By "uncovering by substitution", I mean a slide transition that doesn't just add or highlight the next element, but which actually changes an existing element. You know, like \alt and \temporal do.

...Ok, so \alt and \temporal actually are beamer commands, so I guess the feature is provided after all. But it's implementation is rather shaky. I mean literally, my slides shake when I use these commands. That's because the alternatives are of slightly different lengths, which slightly displaces the remainder of the text, which makes an unpleasing shaking effect if I use several alternatives in quick succession. Again, most people probably aren't bothered by this at all, but I'm the obsessive type who wants the "presentation" part of his presentations to be exactly right.

As you must have guessed by now: here's my version of \alt. It's called \switch, and just like \uncover, it doesn't shake. Furthermore, it's argument is a list of \case<+>{...} clauses which will appear one after the other. Or at the same time, if you use overlapping ranges. That's both more general and more useful than \alt and \temporal, which are limited to two and three non-overlapping ranges, respectively.

And now that the extent of the possible has been increased once again... a new level of time-wasting attention to details can begin.

Tuesday, October 21, 2008

Designing a mergeable filesystem structure

In my previous post, I have argued that it would be better if filesystems could be merged without human supervision. This could only happen if conflicts were impossible, but with today's filesystems, merge conflicts are actually inevitable! Let's design a filesystem without this flaw.

My study of conflicts has led me to the study of a family of data-structures which I call commutative types. These structures are abstract data types, in the sense that you can only modify them through their public methods. What distinguishes commutative types is the additional restriction that the internal state of the object must not depend on the sequence of operations which have been performed on it so far, but on the set of operations which have been performed. In other words, the order in which the operations are applied must have no impact.

For example, consider an object whose internal state is a single integer. If the only update operation provided were increment() and decrement(), then this object would be commutative. This is because incrementing and then decrementing yields the same result as decrementing first, then incrementing (we're ignoring overflows for now). Similarly, if double() and triple() were the only operations provided, then the object would again be commutative. On the other hand, if the same object allowed both increment() and double(), then that object would not be commutative.

x + 1 − 1 = x − 1 + 1
x × 2 × 3 = x × 3 × 2
(x + 1) × 2 ≠ (x × 2) + 1

Integers are well studied structures for which commutative operations are known, but in order to represent a filesystem, we will need a commutative object with a much more complicated internal state. Let's design one! What are the requirements?

Well, here's an easy one. Suppose we write() a value in a particular file. If we later read() this same file, then we ought to obtain the value we wrote in it. Now, if we read() the file before we write to it, there's no way we're going to read the same value. Does this mean that any filesystem supporting both read() and write() can't be commutative?

...

Yes and no! It was a trick question. Remember, we're only concerned about the internal state of the object here. Since read() doesn't change this state, it actually commutes with anything. In particular, read() commutes with write(). Unfortunately, this still doesn't make the filesystem a commutative object, because write() doesn't commute with itself...

If we write("foo") to a particular file, then write("bar") to it, then the final state definitely isn't going to be the same as if "bar" was written first. So our commutative filesystem can't even have a write() method.

That's a pretty drastic restriction! We could, however, have a write_xor() method. Instead of replacing the file's contents with its argument, write_xor() would bitwise exclusive-or the content of the file with it. This looks weird and useless, but it would actually produce an okay filesystem. You could still write any value you wanted to the file, you would just need to zero-out the file first, by xor-ing the file's contents with itself. Writing a shorter value in this fashion would leave a padding of zeroes at the end, but we could introduce an end-of-file character to alleviate the problem. All in all, I'm not too dissatisfied with this minimalist interface. And it commutes! You will never see a merge conflict again!

...in theory. But in practice, the result of a merge will be an unreadable mess of binary characters, which is even worse than a conflict. I'm not giving up yet, as I've got plenty of other ideas, but let's keep this so-so idea for now. Because there's another challenge to solve: directories!

If the two branches we want to merge both define the same filename, but one as a file and the other as a directory, what should we do? Should one take precedence over the other? That would work, and it would probably commute, but I have a better solution. What if we kept both? With today's filesystems, every directory's got two names: /foo/bar and /foo/bar/. The first form is usually favoured, out of habit more than anything else, I think. Well, let's not let the choices of the past prevent us from picking the choice of the future today. I'll allow /foo/ to contain both a file named bar and a directory named bar/! And my trees will commute at last!!!

Wait, I do sound more crazy than usual when I say it like that.

Sunday, October 19, 2008

Rant against merge conflicts (and a solution strategy)

Version control used to be all about versioning. I never used RCS, but I bet the killer command was something like "rcs commit", to create a new version.

Projects soon grew bigger and version control began to be all about collaboration. The killer command was then "cvs checkout", to get the source and begin collaborating.

Then projects grew even more complicated and it was no longer sufficient just to version text, it was now important to version binaries and directories and symlinks and permissions and ancestry. As version control began to resemble filesystems, the magic occurred in commands like "svn add".

More recently, different distributed version control made forking much easier, and the killer command is now "git branch". But the future of version control, I believe, lies in the one command which never worked quite right: "git merge".

Because of merge conflicts, merging is the only version control command which requires human supervision. Removing this constraint would allow other programs to perform merges, a seemingly small advantage which, in the long run, could actually lead to some very useful and unexpected applications... I'm thinking about unionfs extensions, but there could be many others. Never underestimate the creativity of a million strangers!

I happen to be somewhat of an expert on conflicts, or at least I wish I was. For my master's thesis, I'm currently tackling weaving conflicts in aspect-oriented applications. My conclusion so far is that conflicts are inevitable, unless we work with very restricted structures which are guaranteed to merge properly. I'm trying to find suitably-restricted structures which would be expressive enough to program with.

I think that weaving and merging are very closely related operations. The first attempts to combine code, while the second attempts to combine filesystems. In both cases, unfortunately, the parts to be combined could turn out to be utterly incompatible. Current aspect-oriented languages tend to proceed with weaving anyway, postponing the disaster until runtime. Current version control systems take the opposite approach, refusing to merge until the user has fixed all of the conflicts. But I think it should be the other way around! Incorrect programs ought to fail as early as possible, possibly during the compilation or weaving phase. And for scripting purposes, as I've mentioned, I'd rather have merging succeed all the time.

For my aspects-related research, I've found several restricted structures which combine fine all the time, but filesystems can't be among them. Thus if we do insist on combining filesystems, I claim that conflicts are inevitable. That's why I don't insist on combining filesystems. In fact, you might remember how a few months back, I wished for a framework customizing the relationship between the git repository and the filesystem. This is precisely what I'm arguing for once again! Let's use one of my magic restricted structures inside the repository, so that merges succeed all the time. Then if users want to use the repository to track their filesystem, their logs, their cats, or whatever, let them write a translation between the repository and the thing they want to track. Now that would be doing one thing and doing it right, rather than letting filesystem concerns creep into the repository's code base.

What do you think? I am being more crazy than usual?

Saturday, October 18, 2008

Rant against choices (and solution)

This is a mashup between Barry Schwartz's paradox of choice talk and sigfpe's presentation of ordinals as a survival game.

Apparently, math tells us that there are three kinds of totally ordered single player games.

  • ∅, where we've got no choices at all. if society gives you this choice, blame society.
  • successor ordinals such as 42 or ω + 1, where you've got many choices, including one which is obviously better. if society gives you this choice, pick the best move and smile.
  • limit ordinals such as &omega, where no matter which choice you make, you could have made a better one. if society gives you this choice, pick as best as you can, then blame yourself for not choosing better.

Barry Schwartz noticed that consumerism yields societies with lots of choices of the third kind, which makes people unhappy. Perhaps his book offers practical solutions, but in his talk he just seemed nostalgic of the days when society gave him choices of the second, perhaps even of the first type. Well, I've got a message of hope for him.

If ordinals are any indication of the evolution of society (!), then we're going to experience an alternation of successor and limit situations, so we're going to be fine half of the time. Society is not going to revert to the old days of the finite ordinals, when there were few enough choices to make correct decisions. Instead, I predict that we're going to have even more choices, but that this time it's going to be pretty obvious which one to make. ω + 1: one step above the competition. Would make a great slogan. Soon after, said competition is going to adopt the new technology and we'll reach ω + ω, another disappointing limit ordinal. Then a new technology will project us into ω + ω + 1, and the first few consumers will experience satisfaction once again.

In short, the secret to happiness is not to have low expectations, as Barry suggests, but to be an early adopter!

Wednesday, August 27, 2008

Google's badware hoop (and solution)

As you've probably noticed, Google began warning users against some websites, making them read through a "this site may harm your computer" message before allowing them to proceed. I'm glad to see you care about me, Google, thanks, but no thanks. I can take care of myself.

The problem is, you can't turn this off.

Until today, of course, since I'm publishing this greasemonkey script. There are other scripts like this here and there, but I obviously prefer mine better. My version highlights dangerous links in red, letting you into the site without asking you to jump into any hoop. In addition, a second link allows you to check Google's diagnostic page, which explains how the hell they could be led to believe that my local tree-hugging eco center switched from wanting to recycle my computer to wanting to harm it.

Wednesday, August 06, 2008

filenamed

Does your shell script use temporary files? Does it clean up the temporaries after it dies? What if the user aborts your script early by using ^C? What if he feels mean and uses kill -9 instead?

Not using temporary files is the easiest way out of this mess, but unfortunately there are situations where this is unavoidable. Let's say, for example, that you want to diff the output of two programs. Using temporary filenames, this can be done as follows.

bash progA > outA.tmp bash progB > outB.tmp bash diff outA.tmp outB.tmp | progC bash rm outA.tmp bash rm outB.tmp

It's possible to use pipes to eliminate outA.tmp

bash progB > outB.tmp bash progA | diff - outB.tmp | progC bash rm outB.tmp

It's also possible to eliminate outB.tmp

bash progA > outA.tmp bash progB | diff outA.tmp - | progC bash rm outA.tmp

But with this technique it isn't possible to eliminate both temporaries at once. To see why this is is a problem, consider the case where progB is stuck in an infinite loop. In that case, the user is justified to kill your script using the magic CTRL-C combination; and even if the action isn't totally justified, the user can do whatever he wants and it's your job to keep your program from fooling up even when the user does. In any case, ^C will kill both progB and your script, which won't have the opportunity to delete its temporary file. It's not a very critical flaw, but I'd feel better if the script was robust enough to withstand this.

A naive solution could be to disable ^C.

bash trap "" SIGINT bash progA > outA.tmp bash progB > outB.tmp bash diff outA.tmp outB.tmp | progC bash rm outA.tmp bash rm outB.tmp

But this will only annoy the user, who will just kill your script using kill -9 instead of ^C. And you can't disable kill -9. So what would be a better solution?

The solution I've been advocating until today is as follows.

bash trap "rm -f outA.tmp outB.tmp" EXIT bash progA > outA.tmp bash progB > outB.tmp bash diff outA.tmp outB.tmp | progC

This will erase the temporaries on exit, whether the exit is normal or due to ^C. It still doesn't work against kill -9, but what does?

Well, I'll tell you what does. If user-mode code can't clean up on SIGKILL (the signal which -9 selects), then we'll use kernel-mode code. Incidentally, the kernel already contains code to clean up unclosed file descriptors, and we can use this to our advantage.

When we used "-" as an argument for diff, it really was just a short name for /proc/self/fd/0 (that is, standard input). This path names a virtual file which is deleted by the kernel when grep terminates. These virtual files correspond to file descriptors, so if we can create additional file descriptors, then we can create auto-cleaning temporary files.

read_fd3.rb fd3, fd4 = IO.pipe read_fd3.rb fd3.getc # wait until fd4 is opened by an outside process read_fd3.rb fd4.close read_fd3.rb exec(*ARGV) write_fd3.rb $stdout.close write_fd3.rb $stdout = File.new "/proc/#{ARGV.shift}/fd/4", 'w' write_fd3.rb $stdout.write 'x' write_fd3.rb $stdout.flush write_fd3.rb exec(*ARGV) bash ( bash progA | ruby read_fd3.rb diff /proc/self/fd/0 /proc/self/fd/3 & bash ruby write_fd3.rb $! progB bash wait $! bash ) | progC

The first ruby program creates two linked descriptors and leaves them open, letting the exec'd program use them. In this case, the exec'd program is diff, and it is told to compare /proc/self/fd/0 against /proc/self/fd/3. The first is just standard input, which comes from progA. The second is one of the linked file descriptors which were left open.

The second ruby program writes to the other linked file descriptor. This effectively sends the output of progB to the virtual file which diff is reading, as needed.

write_fd3.rb also writes an additional byte before the transfering the control to progB. This byte is needed because the end-of-file only occurs once all programs have closed all of their handles on the virtual file. read_fd3.rb has one of those handles, but it cannot close it until write_fd3.rb has secured its own handle, or the end-of-file will come too soon. So write_fd3.rb sends one byte to tell read_fd3.rb that it is now safe to close its handle.

You'll notice that this virtual file strategy is a bit awkward to use. And now that you have learned how to do it by hand, I can reveal you a secret: this strategy was built into bash all along! The syntax is as follows.

bash diff <(progA) <(progB) | progC

Concise, isn't it? However, this isn't the end of the story. There are some programs, unfortunately, which look at their input multiple times. You can't do that. Closing /proc/self/fd/3 is just as irreversible as closing stdin! And you can't use fseek(), either. So sorry, virtual files freed by the kernel. I tried to make this work, I really did, but... you're ordered, I'm random. We're just not made for each other.

Here's a more flexible solution. If the dying process cannot cleanup, then another process should take care of it. Preferably, a process which always runs, a daemon process. Whose job is to allocate and delete temporary files. A given client would reveal its process-id to the daemon, which will allocate a file for the client and delete it once the process with the given process-id has disappeared from the system. It could have disappeared for different reasons, including normal termination, ^C, and even kill -9.

If you think implementing a daemon would be going through a lot of trouble just for a few temporary files, then you'll be happy to hear that I've already went through this trouble for you. I called my daemon filenamed, and the corresponding client, filename, can be used as follows.

bash diff $(progA | filename) $(filename $(progB)) | progC

I also provide a wrapper called "<", which can be used as a drop-in replacement for the bash syntax <(...) which I introduced earlier. My version, of course, allows fseek().

bash diff $(\< progA) $(\< progB) | progC

There are a few aspects of my daemon which I'm not that proud of, but which I don't intend to fix. First, it depends on ruby, even though it's use is not ruby-specific. I'm just too lazy to reimplement it in C. Second, it's not very secure. Clients shouldn't be able to take control of the daemon, but they could easily request it to keep files until process 1 dies, that is, forever. Clients shouldn't be able to modify the files of other clients, but they could easily read them.

If you can live with that, enjoy!