## How Haskell helped me write a correct algorithm I didn’t understand

Here’s a toy problem with a goofy setup: at a certain company, everyone tries to avoid responsibility, so whenever anyone gets any kind of request, they just pass it along.  Each person has a fixed list of people to whom they delegate all their requests; each request goes to everyone on the list.  Of course, some people are so junior that they have no delegates, so they have to do all the work.  The question is whether, given a particular such setup, there are some requests that simply fall into an endless cycle.  That is, whether there is a person A who forwards to (among others) B, who forwards to C, …, and eventually back to A.

This problem has all sorts of serious applications, but those don’t matter here.  What matters is an algorithm to solve it.  My purpose in this post is to present such an algorithm in Haskell which is correct, and for the right reasons, but for which I didn’t know what those reasons were at first.  Nonetheless, by using standard Haskell typeclasses, I was led to write code that expressed those reasons.

I’ll begin by laying out the types that express the problem.

```import Data.Map (Map)

type Delegate = String

data DelegateError = DelegateMissing Delegate | DelegationCycle Delegate

checkDelegations :: Map Delegate [Delegate] -> Either DelegateError ()```

This is simple enough.  Now, the natural language version of the algorithm I want to use is to “slurp” the delegations map like a straw, lifting the lists of delegations back along the chains of delegation, checking as I go that no list passes anyone on that list.  To make this a technical reality, I observe that at any time in this process, a particular delegate can be in any one of three states:

• In possession of a nonempty list of other delegates (the normal state)
• In an error state: either known to be part of a cycle or known to have requested a delegate who for some reason isn’t in the map
• In possession of an empty list (that is, done)

Although the first and third states need not be separate, and indeed in the definition below they overlap, I will point out soon why it’s important. Here are the types that encapsulate this overview:

```{-# LANGUAGE DeriveFunctor #-}
data SlurpState a = Normal a | Fail DelegationError | Done deriving (Functor)

slurpOnce :: Map Delegate (SlurpState [Delegate]) -> Map Delegate (SlurpState [Delegate])```

Why do I parametrize `SlurpState` and make it a `Functor`?  I’ll explain that also.

To use this in `checkDelegations`, I’ll need a way of deciding the overall state of a `Map Delegate (SlurpState a)`; that is, I want a function of type `Map Delegate (SlurpState a) -> SlurpState a`.  That’s obviously a fold of some kind, so I need a combining operation `SlurpState a -> SlurpState a -> SlurpState a`.  This suggests that I ought to make `SlurpState a` a monoid.  Well, it suggests a semigroup, for which this operation is the only requirement, but making it an instance of `Monoid` means that I can use the `foldMap` function from `Data.Foldable`, since `Map` itself is an instance of `Foldable`.  Here, then, is the instance I want:

```import Data.Monoid

instance (Monoid a) => Monoid (SlurpState a) where
mappend x@(Fail _) _ = x
mappend _ x@(Fail _) = x
mappend (Normal x) (Normal y) = Normal (x <> y)
mappend Done x = x
mappend x Done = x
mempty = Done```

Now, why is this the instance I want?  Because you can never undo an error, and you’re not done unless everyone is done, and otherwise combining two lists of delegates is just putting them together.  I’m making a bit of a space/time trade here by not taking the `nub` of this concatenation, so there may be duplicates, but that’s fine: as long as both `x` and `y` are subsets it’s correct.

I can now provide a definition for `checkDelegations`:

```import Data.Foldable
import qualified Data.Map as Map

checkDelegations dMap =
case foldMap (const [] <\$>) dMap' of
Done -> Right ()
Normal _ -> checkDelegations dMap'
Fail e -> Left e
where dMap' = slurpOnce dMap''
dMap'' = map Normal dMap```

As you can see, I have employed the `Functor` instance of `SlurpState`.  The reason for this is that when folding, I really don’t care about the list of delegates (as you can see from the pattern matching); I only care about the high-level state. Since I don’t care about it, it is inefficient to compute it, so I just zero it out, leaving only the constructor.  This is why I need the `Done` state: it could be replaced by `Normal []` as far as `Monoid` is concerned, but then I wouldn’t be able to distinguish it from any other normal state in this code, leaving me only the inefficient option.  I suppose the alternative would be to map to some other monoid with only two values, but there isn’t an obvious one available.

Perhaps a more Haskellish reason is simply that using `Normal []` to mean completion is not well-typed, and my type should be more finely granular to reflect what’s going on in the algorithm.

Here, at last, is the real work, the definition of `slurpOnce`:

```slurpOnce dMap = Map.mapWithKey shiftState dMap
where
shiftState delegate (Normal delegates) = checkCycles \$ foldMap id \$ map getDelegate delegates
where
getDelegate d = Map.findWithDefault (Fail \$ DelegateMissing d) d dMap
checkCycles x@(Normal delegates) =
if elem delegate delegates
then Fail \$ DelegationCycle delegate
else x
checkCycles x = x
shiftState _ x = x```

Aside from the parts that actually concern the validity of the delegates map, the interesting feature here is another, perhaps unexpected appearance of `foldMap`.  It is necessary because `dMap` here contains not `[Delegate]` but `SlurpState [Delegate]`, which is only sometimes a `[Delegate]`.  However, its monoidal append does exactly what we want; in fact, it is here that we use its case that actually appends lists.

Here is where I realized I didn’t know why the algorithm terminates.  I mean, I check for `Done` in `checkDelegations`, but I don’t write `Done` anywhere in `slurpState`, and the map is initialized to all `Normal`, so where does it come from?  I’ll leave you a moment to think about this.

The answer is that `Done == foldMap id []`,  so whenever one of the delegates has nothing, its state moves to `Done`.  This is, of course, exactly what `Done` means, and it agrees with my earlier comment that we could replace `Done` with `Normal []` if we weren’t deriving `Functor`.  This is in hindsight, of course; I didn’t design the type this way.  In fact, the only reason this works at all is that `Monoid` must have an `mempty`, and that `mempty` is the monoidal sum of the empty list.  That `mempty = Done` is natural from the semantics of the equivalence between `Done` and `Normal []`; that is, even though I wasn’t thinking of this equivalence, I was thinking of the meaning of `mappend`, which reflects it.

So that’s my story of how Haskell had my back.  Even though the algorithm is inherently procedural (it doesn’t use laziness, nor real recursion, nor does it pass around anything but data types), because Haskell so nicely abstracts procedural operations like loops as folds with various typeclass constraints, I was led to ask what typeclass described what I wanted to do.  That class required a neutral value that the fold handled properly, so simply the fact that I’d framed the problem the right way meant that I couldn’t help but write the right code.

## Right to kill

Guns and gun rights in America are a big thing in the news right now because of the Connecticut kindergarten massacre, and although this causation is right and good, it is of course unfortunate that such things are taboo at other times.  This is acknowledged daily by those who wish it were otherwise.  To me, what is truly appalling is the everyday acceptance of the gun-rights position that owning a gun is an acceptable means of ensuring the safety of you and (supposedly) your family.  The author of this Op-Ed, for example, finds that to be the case.  I don’t deny that self-defense is a right, but I do deny that there is a right to kill.

It is not true that everyone agrees that it is not right to kill; that is, there are many situations where almost every American would say killing is somehow acceptable.  Combat during war is one example (war itself is also thought to be acceptable); executions are another one that is still more popular than it deserves to be.  Self-defense is the ultimate example, though, for a killing in self-defense by an ordinary citizen is legally excusable: there is no other place in American society where any person can kill any other person given only that the latter might have been attacking them.  I know why this is so: because if an assailant comes at you with the intent to kill or at least to make you despair of surviving the attack, in the heat of the moment you should not be held responsible for finding their life to be worth less to you than your own.  And, therefore, the law excuses you and upholds your judgment that indeed, they were not deserving of life.  This is sort of an “oops rule” for getting into a big fight.

This weighing of souls extends many-fold into the situation where you are protecting someone else, or perhaps many people; just as a killer is multiply execrated for multiple victims, a killer-in-self-defense is multiply exonerated for saving them.  I have no idea how this germ of utilitarianism has gotten such cultural approval when the general feeling is that the “greatest good for the greatest number” is either repulsive, communist, or heartless.

This “oops rule” for killing in self-defense is both illogical and oblivious.  It is illogical for several reasons, the first being that once a fight becomes a life-or-death struggle, both parties are acting in self-defense, and thus, whoever wins, their act of killing should be excused.  Consequently, neither the original attacker nor the original victim can be said to be in the wrong so long as the fight becomes deadly.  One could object that the instigator of the deadly fight is responsible for inserting deadly force where it did not exist before, but I am skeptical that it is that easy to discern a true intent to kill and distinguish it from a bluff, a threat, or an intent to merely injure—particularly for the frightened victim.  And if the victim is carrying a gun, they may be better equipped to threaten the attacker, but if that doesn’t end the fight, it automatically becomes deadly; so carrying a gun with the intent to use it in self defense is actually excusing any attacker from guilt in trying to kill you.

It is, of course, possible that the attacker is unambiguously acting to threaten the life of the victim, say by strangling them.  This leads to the second source of illogic: that the victim is not expected to prove an attempt to end the attack non-lethally.  It is probably more difficult to kill someone than it is to beat them away, though almost no one is trained in self-defense (and those that are, are also told to run away from fights when possible.  This is good advice for people whose lives do not frequently include fighting).  Regardless of circumstances, if resort to killing is the first course of action then the actor loses my moral sympathy.  Of course, few people would jump immediately to a credible killing threat, but my point is that it is not expected of people that they do not, and therefore it is accepted if they actually do.  And the barrier to killing drops if one is armed with a weapon whose every use is an act of lethal force.

The reason the “oops rule” is oblivious is that it puts moral and legal judgments in the hands of people who are not to be trusted with them in circumstances when they are especially not to be trusted.  It also makes a right of something that most people are psychologically not equipped to handle doing, either before or after.  (And those who are, are a special issue.)  It may be possible to train people to think clearly and legally about the issues, just like it is possible to train people in the use of guns.  However, the more allowances are made for a person’s training, the more trust is placed in that person, and in this issue, the trust concerns something that is the province of the judicial system.  If more training is an excuse for allowing people to kill in self defense, then administration of the law is placed in the hands of arbitrary citizens.  Taking the law into one’s own hands is the enemy of civilization.  Since administration of the law is the domain of certain government professionals, so is protection of the citizens.  It would truly be the decay of civilization of government were unable to do that, but asking the government for the right to take over its job is admitting its power over you to prevent that, and in that case, it should.

The right to own guns is being defended on the practical grounds that would-be gun owners have the right to protect themselves with them (it is also defended on the impractical grounds that the historical culture of the United States at the time of the Revolution included gun ownership, but that is literally neither here nor there).  A gun is a lethal weapon and cannot be anything else: a gunshot wound to any part of the body can cause deep and extensive tissue damage that is either outright deadly even to non-vital organs, or a serious medical challenge to heal.  An assault with a gun is always assault with the intent to kill, no matter how skilled a marksman the shooter is.  Therefore the right to carry a gun is the right to kill.

Posted in Uncategorized | Tagged , , , | 1 Comment

## A response to “Is Algebra Necessary?”

As a mathematician, I did not even reach the second page of Andrew Hacker’s opinion piece “Is Algebra Necessary” in today’s New York Times before reaching for my mouse to record some of his more egregious howlers as quotations for this post.  The entirety of his opinion reflects a truly dangerous thread of thought in American education: that the actual contents of an academic discipline are accountable to the people on the grounds of future value, and that every moment of teaching should be justified as providing specific means to a particular vocational end.

The entire article must be understood in the light of the following sentence:

But for most adults, it [mathematics] is more feared or revered than understood.

Mathematics in school is advanced as being a subject of import and mystery: basic algebra is dragged out over many years with “prealgebra” and still apparently fails to result in being learned by many students. What does result is that these people come to wonder what is so great about math, what is the point of learning it, and this attitude affects even people such as Professor Hacker, who can claim some experience that would actually yield a positive answer to those questions.  It is a malaise that is familiar to research mathematicians: the feeling that “I don’t use that field and it’s therefore boring and pointless”.  I will return to this later, but for now, let it set the tone for the rest of this post.

Professor Hacker speaks of a “nation’s shame” that mathematics classes are preventing 25% or more students from finishing high school, with South Carolina and Nevada being given as examples of the “more”.  So when he observes that:

It’s true that students in Finland, South Korea and Canada score better on mathematics tests. But it’s their perseverance, not their classroom algebra, that fits them for demanding jobs.

it must mean that our nation’s shame is a lack of perseverance, and that the demands of today’s favorite jobs should direct that perseverance through the curriculum.  But if pure doggedness is all it takes to succeed, why go to school at all?  Professor Hacker suggests that there is a minimum level of mathematical competency still to be desired:

Of course, people should learn basic numerical skills: decimals, ratios and estimating, sharpened by a good grounding in arithmetic.

This common reduction of mathematics to the purely numerical is a position taken in ignorance.  It is one informed by the idea that these aspects are the real insights of mathematics into the everyday world, which is all that matters.  What about the investigation of process and algorithm (computer science)?  of systematic analysis (algebra and logic)?  of the imprecise and changing (calculus)?  of visualization, similarity, and even analogy (geometry)?  What about the use of complex numbers in engineering, if the practical is what is to be sought?  This subject can barely be understood without basic algebra.  Professor Hacker’s generous allowance that numeracy is the basis of mathematics is a position abandoned by the world three or four centuries hence.  But he answers my objections:

But there’s no evidence that being able to prove $(x^2 + y^2)^2 = (x^2 - y^2)^2 + (2xy)^2$ leads to more credible political opinions or social analysis.

This sentence is nothing more or less than “I don’t use that field and it’s therefore boring and pointless.”  I would not expect a political scientist to place a lower priority on the formation of political opinions than on the verification of an algebraic identity, but perhaps he has not considered what goes into doing either.  First, a discussion of $(x^2 + y^2)^2 = (x^2 - y^2)^2 + (2xy)^2$: this is a special case of the more general and more famous identity

$(x^2 + y^2)(z^2 + w^2) = (xz - yw)^2 + (xw + yz)^2$

in which $z = x$ and $w = y$.  Both can be proven by performing the operations indicated on both sides and rearranging terms until they are equal.  Both can also be proven using a clever interpretation of the sum of squares as the squared length of a complex number and using the fact that lengths multiply in products of numbers.  Each method has its virtues:

1. The purely computational method requires the ability to understand an inexpressive spread of symbols as indicating a process, namely the process of squaring some expressions.  It requires the ability to follow a logical sequence, namely the sequence of applying the rules to perform the process.  And most crucially, it requires the ability to recognize patterns in the result: namely, the pattern that $(x^2 + y^2)^2 = x^4+ 2x^2y^2 + y^4$ and $(x^2 - y^2)^2 = x^4 - 2x^2y^2 + y^4$ share the terms $x^4 + y^4$ and therefore one can be converted to the other by altering only the middle term, which is what appears as $(2xy)^2$.  Completing this proof—really completing it—is an exercise of several kinds of insight.
2. The complex numbers method is simply that $(x + iy)(z + iw) = (xz - yw) + i(xw + yz)$, and that the operation of replacing an expression $a + ib$ with $a^2 + b^2$ leaves the equation valid.  Understanding this proof is understanding that while there may be an ordinary reason for an equation to be true, coming just from comparing both sides, there can and perhaps should also be an extraordinary reason, one that has its roots in something larger and more significant.

The first method alone contains valuable lessons that, frankly, I do not see in many of those who are supposed to lead the United States or of those who are supposed to make informed decisions in electing them.  Politics is full of superficially logical lies and disingenuous half-truths; it should be within the capabilities of every citizen to figure out if some claim that “once the government requires us all to buy health insurance, it will be able to say who lives or dies” is derived logically from anything factual, and if so, from what facts.

The second method is a rare gift in social policy.  It is the gift of seeing past the details of who should pay for health insurance (or perhaps, what particular crumbs of mathematics should be taught in school) and having a vision where everyone gets it at all.

For these reasons I can only revile the following statement:

Mathematics is used as a hoop, a badge, a totem to impress outsiders and elevate a profession’s status.

After all, a subject that is of no use but is “feared and revered” by most people can only be fakery.  The imagery of mathematics as idolatry pervades Professor Hacker’s conception of the subject.  Given what I wrote above I trust the reader to understand why I will not respond further.

Thus mathematics teachers at every level could create exciting courses in what I call “citizen statistics.”

I am wholly in favor of replacing the mathematics curriculum.  Currently, school math is a limited and repetitive sequence of ill-chosen subjects drawn from the 19th century curriculum and presented as representative of a subject that has grown enormously both in its pure and its applied aspects.  But the proposal that algebra (and presumably geometry and calculus, not to mention poor outdated trigonometry) be replaced by the equally limited offering of what I could call “statistics for newspaper readers” is not sufficient.  This is one thing—one thing—that one must be able to do after making a claim to have a mathematics education.  Just like being able to formulate and execute simple algebraic procedures is one thing to do.  Just like trigonometry was one thing that was highly applicable to employment in the Renaissance if one wanted to be a sailor, though it is of no practical use now.  Professor Hacker claims that this is not “dumbing down” the subject but it is: it is reducing the literal universe of mathematics to a single application that can be taught to attentive students in a year or two, but will no doubt be spread across twelve and watered down with soft goals such as “numeracy” that can never be attained without a complete immersion in a variety of ideas.  This idea is the idea that there is a magic bullet that will kill the fear of mathematics and raise our students to a higher standard of understanding.  My view is that if we are to expect more, we should teach more, and not less.

Why not mathematics in art and music — even poetry — along with its role in assorted sciences?

Any research mathematician will probably volunteer the opinion, unsolicited, that mathematics is an art rather than a science.  In the sciences it is one step away from any direct application, that step being the experimental or interpretive layer furnished by the science itself.  As an independent practice, math is the science of ideas.  This very fact is why we should not pursue a curriculum that strips math of all its ideas and variety, all the art, and teaches only a short-sighted distillation of what the current trends in our economy need for day-to-day work.

Nor should we say, though, that “math is just an art” and put it on the same footing as the arts.  For one, “just an art” is a denigration reflecting the place occupied by the various unserious subjects in schools now, subjects forgotten after the fifth grade when they are replaced by ones that are “of use”.  It is certainly the case that new math was first discovered in art, such as projective geometry, but to make that lesson a mathematics lesson requires more than description or observation; it requires analysis, and that is something that takes place at a higher level than simply learning the facts of how math is used in art.

But there is no reason to force them to grasp vectorial angles and discontinuous functions.

Professor Hacker chose this sentence as his conclusion, and I will make the response mine.  There is every reason to force our students to grapple with, and ultimately grasp vectorial angles and discontinuous functions—two examples that I could not imagine being more poorly chosen for his purposes, as linear algebra (the study of vectors) is the single most applied portion of algebra, including in Professor Hacker’s beloved statistics, and discontinuous functions are the kind of function that occurs most in measurements, any kind of engineering being an example.

But applications are of passing importance.  These concepts are elements of the act of learning something new: inhabiting its world of ideas, combining them and dissecting them, investigating their consequences and following the implications wherever they may lead.  If mathematics is indeed a liberal art, and if it is ever to give our students practicable skills, then this is what it can give them, and if they can’t be expected to “grasp” that idea, they will certainly never grasp the more vague and deceptive ideas that pervade the world for which they are supposedly being prepared.

Posted in Academia, Math, News, Politics, Responses | 1 Comment

## An ending to the Wheel of Time — illustrated

I love the Wheel of Time, but my first encounter with it was a piece of mildly ironic real-life foreshadowing.  My mother apparently picked up Eye of the World on the recommendation of a teenager she ran into while looking for books for me, but I left it sitting on my desk for a full month before venturing to open it.  Why?  Because the cover picture was a little goofy.  They did not altogether improve over the course of the series, and this was a source of friendly amusement among the fans.

Until today, my favorite one of the covers was Lord of Chaos — possibly not coincidentally, also my favorite one of the books.  Also the last one I didn’t have to wait for.  However, my favorite cover is now this one, the cover of A Memory of Light, which I am having a hard time waiting seven more months for.  What’s good about it?  Here are some things:

• Rand looks good.  No, he looks perfect: he is tall and handsome, but his face is grim; he seems to be in his thirties until you look closer and realize he could be much younger.  Just as he is supposed to be.  Also, his pose is terrific: you can see him in the act of striding over the rough cave floor, drawing his hand up to protect himself from something.
• Nice symbolism: he is holding Callandor, the crystal sword, over his eyes like I would hold my hand up to shade my face from the sun.  However, he is looking into Shayol Ghul — that is, into Hell.  It’s dark in there.  He is using the sword of Light to protect his eyes from the Shadow.
• There’s a full solar eclipse in the background, something that was hypothesized for a good many years hence.  A nice shout-out to the prophecy (“Twice dawns the day when his blood is shed; twice to live, and twice to die.”  Yes, I did that from memory), which also, I think, tells us what is going to happen in this scene. Edit: Turns out I remembered both lines of the prophecy correctly, but pulled them from different places!  The correct partner for “twice dawns the day” is “once for mourning, once for birth”.  But then it goes on to talk about his blood staining the rocks of Shayol Ghul, so I’m still right.
• More decent-looking people in the background!  Blue and Yellow Aes Sedai; I’m guessing Moiraine and Nynaeve?  Or Egwene, but she shouldn’t be there and wouldn’t identify as Blue anyway.  And  I thought Nynaeve had a long braid.   I only read Towers of Midnight once, so I forget if she cut it off.  Or perhaps she will cut it off in the next book.  Mourning for Lan? Edit: She lost it in her Aes Sedai test.  I really liked ToM; perhaps I should go read it again.

My complaints?  Trivia:

• I believe the rocks of Shayol Ghul should be black, more evil-looking.  As drawn they look just like normal rocks.
• The clouds above Shayol Ghul do not look nearly ominous enough.  Unless Rand’s purifying influence is clearing them, they should be black shot with silver and maybe red.  I’m imagining nuclear fallout here.

But you know, if it weren’t so good I wouldn’t bother to complain about such small things.  Instant classic.

Posted in Book reviews, Not complaining, Wheel of time | 2 Comments

## Ubuntu on a netbook screen — revisited

In my very first post (other than that abortive book review), I gave what I thought was a very clever way of getting `xrandr` panning to work in Ubuntu with the Unity desktop. Like all good solutions, it worked as much as possible with the available high-level tools, avoiding any kind of reinventing the wheel or tinkering directly with the X server — other than using `xrandr` in the first place, which is unfortunately necessary given that there is no other way to get the panning effect. I seem to recall a developer in some bug report complaining that this ought to be a feature of the compositer, and I agree.

Reality intruded when my perfect solution was destroyed by bugs. Every Ubuntu upgrade is a new and exciting opportunity to see how they have ruined something minor but irritating with an unrelated “fix”. In my case, the “Display settings” of Compiz no longer had the desired effect upon the screen, instead producing garbage. So I had to abandon panning for months. Now that I’m using Ubuntu 12.04, I thought I’d try it again and see if my bug report had any effect.

Surprisingly, it did! No more garbage was produced. Alas, this time, `xrandr` itself was felled by a bug caused by a “fix”; as I understand it, they were trying to prevent the mouse from going out of bounds under some circumstance, and ended up preventing all panning entirely. After some Googling, I found a useful bug on Launchpad, with (O miracle) a useful solution.  Simply install that PPA (a custom package repository), upgrade the X server, and panning will work again.

That was, of course, just the start of the journey, because it became necessary to tweak the clever solution.  You see, a different bug (whose nature I do not know) reared its head: now, whenever I resumed from suspend, the effect of `xrandr` is negated! Further Googling revealed that the directory `/etc/pm/sleep.d` contains scripts that are run upon suspending and resuming, and I made one that called `xrandr` with my preferred settings.

Nothing happened; `xrandr` claimed it could not find the display. After some kind of inspiration, I somehow learned that this was because it was being run as root, rather than my user, so I wrapped the call in `su -c`. Nothing happened; `xrandr` couldn’t open the display. This was an easy one: `DISPLAY` was not set; I set it to `:1.0`, which is what my shell said it was. Note: default is `:0.0`, which should have clued me in to something strange going on, since I have only one screen. Anyway, still didn’t work, though visibly, something was happening: the screen would refresh, and then refresh again, as though the panning was being reverted after being applied.

Fortunately, a look at the background made it clear that (somehow) what had happened was that the panning was applied before the desktop background was painted, and this somehow reset the display. So I put in a `sleep 5` just to be safe. Nothing happened; same problem. `sleep 10`; same problem. It occurred to me that, even though my script was literally the last thing to run during the resume process, it might be that it was blocking the very thing that was causing the problem, so I wrapped the sleep in a background process, and that fixed it. Whew!

Well, not quite. The next day I gave a lecture in class, using Beamer as usual, and of course, plugging in the external monitor (the projector) screwed everything up and afterwards, my resume script failed again. Very mysterious! It claimed it could not find the display once more; checking back, I learned that `DISPLAY=:3.0`! I guess the monitor caused a new display to be created, and then unplugging it caused yet another one. But now I had the problem of figuring out how to figure out the “real” display, since apparently no predetermined number was guaranteed to work.

This is really annoying, by the way. If a script is not called by some descendant of the X server, it really has no way of knowing what the “real” display is; in fact, there is no well-defined answer to this question in general! The X server could be serving several displays, or something remote, or whatever. You can’t just ask it, you can only be told upon process creation what display you are attached to, if any. But Google once again revealed the existence of a Unix-y solution: the `/tmp/X11-unix` directory, containing a bunch of socket files corresponding to each X display! In my case, there were four (0–3), of which only the last one produced any results from `xrandr`.

At that point I gave up for a day, but earlier tonight, I realized that the obvious solution, given that I only intended to be resuming with my laptop’s natural screen active, was simply to find the latest display and go with that. So I had my script set `DISPLAY` by just looping down the list, probably a dumb way of doing it. That works now.

Oh, did I mention the other problem with the projector? You may recall that my clever Compiz solution was to have it create two “outputs”, one of size 1024×768, and the “real” one of size 1024×600, or more specifically, of geometry specification 1024×600+0-168, which is to say, 168 pixels up from the bottom-left corner of the big display.

Problem is, that solution only works if the big display really is 168 pixels taller than the screen. Otherwise, I just lose that much in a strip from the bottom, and that’s exactly what happens when the display gets resized for the projector (since I have it sync the outputs). I have this vague memory of just re-enabling “detect outputs” back in the fall, and I guess all winter I wasn’t using panning at all, but I have no idea if I got around this problem some other way in the past.

This pissed me off, since it seemed like that was the way of setting the outputs, but then it occurred to me that I could just as easily make 1024×600 the default output and set the other one at 1024×768+0+-168; yes, that’s a +-. It means to go below the bottom of the screen. Obviously, this correctly communicates my intent.

Was that complicated enough for you?  In summary, I need:

• A script to set panning, say in `~/bin/xrandr_panning`:
`xrandr --fb 1024x768 --output LVDS1 --mode 1024x600 --panning 1024x768`
• An autorun script (set however your window manager does this, probably gnome if you are running Ubuntu) that calls this script on startup.
• A suspend/resume script, for example `/etc/pm/sleep.d/00_xrandr` (modify the user name for yourself, of course).  Do make sure that it is executable:
```#!/bin/sh

case "\$1" in
suspend|hibernate)
;;
resume|thaw)
# Just pick the last DISPLAY enabled
# for some reason it sometimes grows
for i in /tmp/.X11-unix/X*; do
j=\$(basename \$i); DISPLAY=":\${j#X}"
done
export DISPLAY
su -c -p - ryanr "sleep 3; ~ryanr/bin/xrandr_panning" &
;;
*)
exit 1
;;
esac```
• Go to the Compiz config manager, and under “General options”, in the “Display settings” tab, set “Prefer smaller output”, uncheck “Detect outputs”, and under “Outputs”, add two:
```1024x600
1024x768+0+-168```

Congratulations!  You now have panning.  Can I “dislike” this post?

Posted in Computers, Netbook, Ubuntu | 8 Comments

## Hyperethicality

I have finally found the stupidest thing I’ve ever read: we should not eat peas because they can talk.  Or rather, we should not exploit peas for our selfish ends because they have some form of chemically-based communication about weather conditions.  Or at least, we should think about whether it’s okay to push peas around just because we want to live, even though they may in some sense also want to live.

The author of this piece asserts as his central thesis that it is worthy of moral consideration whether we should make objects of certain life forms that are found to have “basic learning and communication” abilities.  In particular, since in the case of peas this communication is about stress, is it okay in light of our tendency towards sympathy for animals that show stress?

The logic that leads from “they can react as a group to their harsh environment” to “we should leave them in peace to exercise their inalienable right to life and liberty” is obviously suspect.  I am not being hyperbolic here: the article refers to plants at one point as “who” and says that they have their own “own intrinsic value or version of the good”.  Nor do I believe the article is a joke, since it closes by encouraging the reader to consider this as a single example of how ethics must be constantly examined.

I suppose I’m falling for the trick by analyzing the article, since that would be exactly what the author wants, but I think it is completely wrongheaded and I will analyze it anyway.

My issue is with the specific ethical position he takes: that it is the capacity to think and feel that separates acceptable foods from unacceptable ones.  Going back a step further, he places his argument in the context of what is acceptable to do with “living beings”, presumably making reference to a commonly accepted principle that morality (or ethics, though I really think he is talking about morality here) stops at that line.  Since it is famously difficult to distinguish the living from the unliving, this is not a firm foundation for anything.  Viruses are not really either; a deceased person is dead but subject to a lot of moral conventions; and a decaying corpse is dead as an animal but full of life in another sense.

In addition, since life is partially characterized as being self-sustaining, it would seem that whether or not a “living being” can learn and communicate, it does not “want” to die.  Any lifeform of almost any significance has some capacity for communication, or at least for receiving communication in the form of its environment, which it discriminates for the purposes of living better.  Through its choices and the changes it wreaks by living, other life in the environment adapts its behavior and the effects of this co-evolution have a suspicious similarity to communication.  If this is the line at which ethics enters, then only plants eat ethically.

Presumably it is only conscious communication that is of concern.  Or at least intentional.  These are again imprecise and fraught concepts, and the article admits that peas and other plants do not actually have a nervous system, as a result of which they cannot have consciousness.  So intention is not a valid concept, and their alleged communication is nothing but an automatic, mechanical response to environmental stimuli, one born of exactly the kind of co-evolution described above.  What is it, then, that makes peas different from bacteria in this regard?  Or, for that matter, from plutonium nuclei undergoing a chain reaction, other than the level of organization?

It’s possible that the true home of this argument is in the conception that peas form a kind of society, and thus that their communication is a kind of altruism, so that it is not just selfish reflex action but in fact a kind of ethical behavior on its own.  This might mean, for example, that peas could make it known directly to us that they wish not to be cultivated and eaten; it would presumably be discomforting to be thus addressed by something you are considering sinking your teeth into.  However, as I’ve already said, it should be assumed that every activity of living things is directed towards living and living well, so nothing actually wants to die (notwithstanding the suicidal), and learning that directly from the horse’s mouth is not really news.  In addition, it is not ethics to restrict your ethical sympathies for those subjects that themselves display ethics.  (That is, “he started it” is not a good defense.)

No, as far as ethics are concerned there is, as the article points out, no simple axiomatic solution — to any problem.  This is because ethics (or more accurately, morality) is fundamentally about what makes humans feel good about themselves, and any attempt to reduce it to a few abstract principles unrelated to humans is going to end up classifying either everything as ethical, or nothing.  Because in the end, not much is related to humans.

In this connection I can’t help but observe that trying to classify “everything” as being either ethical or unethical, and to get a meaningful answer, is mathematically hopeless.  You see, we would like the set of all ethical sets of decisions to be closed under unions and under containment; to be free of contradictions, meaning that no set and its complement can be ethical; and for everything to be either ethical or unethical.  We call this an “ultrafilter” and if you are trying to classify, say, “kinds of food” as being ethical, well, there are only finitely many kinds of food and every finite ultrafilter is principal, meaning that a kind of food is ethical if and only if it contains one particular piece of food.  The result is that you end up trying to decide whether a single piece of food is ethical, and honestly, that decision is completely arbitrary.

So as far as the main point of the article goes, the only thing I really agree with is that people have to decide morality for themselves, because any attempt to be philosophical about it is just bullshit.

Posted in Book reviews, Math, Miscellaneous reviews, News | 3 Comments

## Ten thousand reputation

If you read my recent post about TeX, you will know that I am a more than casual contributor to tex.stackexchange.com and have a possibly-obsessive interest in that typesetting language, largely from a programming perspective.  In the last month alone I have gained 3,000 reputation on that site—about 100 per day, in what has for the last week or so been an intentional drive to hit 10,000 total.  Today I have reached that goal.  This gives me the status of a moderator (at least, in privileges if not title). Continue reading