Sunday, November 21, 2010

Mutual






a sweet image... thanks xkcd.

Sunday, October 10, 2010

Saturday, July 17, 2010

Cheating in soccer

An excellent short article by philosopher Peter Singer of vegetarian-activism fame.  BTW, Project Syndicate is the best source of current-events articles I've ever found on the internet.  Common contributors are Ken Rogoff, Simon Johnson, Barry Eichengreen, Nouriel Roubini, Raghuram Rajan, Joseph Stiglitz, Jeffrey Sachs, Brad DeLong, etc.

Friday, July 09, 2010

Beautiful evidence

I was recently in NYC with my mom looking for an apartment.  We walked into Edward Tufte's new studio near Chelsea Piers.  He happened to be there, and gave us a short tour of his studio and showed us his new art, mostly involving his Portuguese water dogs.   Here's an image, lifted from Philip Wadler's blog, that I think he'd enjoy.


Strategic defaults

I was happy to see my home town, Los Altos, CA, in the NY Times today.  (The article was about foreclosures in the area, but still...)  The article really upset me though.  How stupid do mortgage lenders think people are?  
Fannie Mae and Freddie Mac, the two quasi-governmental mortgage finance companies that own most of the mortgages in America with a value of less than $500,000, are alternately pleading with distressed homeowners not to be bad citizens and brandishing a stick at them.


In a recent column on Freddie Mac’s Web site, the company’s executive vice president, Don Bisenius, acknowledged that walking away “might well be a good decision for certain borrowers” but argues that those who do it are trashing their communities.
Do they think that their sanctimonious moralizing will affect anyone?  Lenders take risks when lending money, which justifies the interest rate on the debt.  They took incredibly bad ones in the years leading up to 2007.  Now crying to the borrowers (and the media) when the bets aren't paying off is despicable.   I only hope people who are in over their head in debt are not swayed by the wolves in sheeps' clothing.  There are plenty of upstanding Google employees who will be happy to buy your house at a discount, and will not be 'trashing the community'.  Fannie and Freddie were the biggest enablers of the housing crisis, buying 80% of subprime loans.  Needless to say, they have no moral authority whatever.

Monday, June 21, 2010

Harper and Crary for America

I was unaware of this great PL T-shirt. I want one, but it was apparently a limited edition.

Monday, June 14, 2010

Awesome visualization

Tallest mountain to deepest ocean trench.

Beautiful quote

"What I cannot create, I do not understand."  - Richard Feynman

Probably my favorite aspects of programming is that it (usually) forces you to understand what you are doing.  There is something special about the feeling you get when you understand an idea so completely you can teach it to a computer.  The first time I can remember feeling this was when I wrote a toy implementation of the simplex algorithm for linear programming.  The first time I read the description I found it really hard to follow.  Only after writing down the types of the operations, and slowly decoding the natural language into code did I feel like I really understood what was going on.  Then it seemed like such a simple idea I was amazed I initially found it so difficult.

Note that the contrapositive is "What I understand, I can create."  Unfortunately, this does not rule out creating without understanding.  I occasionally take algorithms out of books without understanding them completely.  While they usually work as expected, I forget how the program works almost immediately, and learn next to nothing from the experience.  It is only through debugging that I gain any understanding of how the program works.  Needless to say, this is an incredibly inefficient way to learn.

Thursday, June 10, 2010

More Polymorphic Recursion

I've been obsessed with polymorphic recursion lately.  I originally just wanted to write a data structure like a list but with efficient insertion on both sides, sometimes called a deque.  The problem is that type inference in the presence of polymorphic recursion is undecidable, in a nice reduction to semi-unification by Herblein.  On the other hand, we don't need type inference.  I'm more than happy to write the type of a function in ML or Haskell, and type checking is decidable with polymorphic recursion. It's sad that SML will never be able to do this.  Apparently OCaml 3.12 will allow it. 

Reading the mailing lists from 1994 when this was being debated on the Haskell mailing list, I found a very interesting example from Mark Jones.  He found that polymorphic recursion would break his implementation of type classes that didn't pass a dictionary at run time.  Without PR, he could statically analyze the whole program and hard code the type class function calls.  He points out with the following that it's no longer possible with PR:

f  :: Eq a => a -> Bool
f x = x==x || f [x]
Note that if I write
data D = D
instance Show D where
_ == _ = False
then calling f D will require infinitely many instances of f. 
 
I also found a good paper by Kfoury et al. showing lots of examples of polymorphic 
recursion in action, and how many of the cases can be overcome using intersection
types (my friend William Lovas' specialty.)

Tuesday, June 08, 2010

The Club

Interesting.  The Club anti-theft device for cars is either bad for society, or your car, depending on the skill of the car thieves.

Sunday, June 06, 2010

Mozart and microbes

Is this for real?

A German company is playing Mozart over speakers to its microbes because it makes them eat sewage faster.

Buying and renting

I've been looking for apartments in New York City recently.  The rents are high.  This is partly due to rent control, but the prices are not very much higher than the Bay Area where I grew up.  Apparently the real estate in NYC is so expensive, even relative to the high rents, that it usually doesn't make sense to buy an apartment.  The New York Times has a handy buy/rent calculator where you can put in the price of the house, cost of rent, cost of mortgage, etc. and it will tell you how long you'd have to own a house before it paid off.  Most of the numbers I tried for the Manhattan apartments I've been curious about never pay off, i.e. it's always better to rent.    Out of curiousity, I was looking around the internet for similar prices in the Bay Area.  Since the interest rates are low now, I thought naturally it would be a better time to buy than when the rates are high.  I was surprised to find the following analysis of my mistake:

It is far better to pay a low price with a high interest rate than a high price with a low interest rate, even if the mortgage payment is the same either way.
  • Your property taxes will be lower with a low purchase price.
  • A low price gives you the ability to pay it all off instead of being a debt-slave for the rest of your life.
  • As interest rates fall from high to low, house prices increase.
  • Paying a high price now may trap you "under water", meaning you'll have a mortgage larger than the value of the house. Then you will not be able to refinance because there you'll have no equity, and will not be able to sell without a loss. Even if you get a long-term fixed rate mortgage, when rates inevitably go up the value of your property will go down. Paying a low price minimizes your damage.
 The prices are presumably lower when the interest rates are high because the demand for housing at a fixed price falls.  I'd like to see if there is really parity in the price of a mortgage for the same house at different times with different interest rates.  Does anyone know a study like this?  I'd be really surprised if the actual mortgage payments were the same.  I suppose you could use Case/Schiller and the historical interest rates to calculate the inflation-adjusted mortgage payments, but I don't have time to do it myself. 

Atul Gawande

I was at a party last night, speaking with a last year anesthesiology resident from the Boston area.  I told her I was reading Atul Gawande's excellent book 'Better'.  She said, "Oh, I know Gawande".  I found this unsurprising, as he is not only a surgeon but a quasi-celebrity with many articles appearing in popular places like the New Yorker.    She continued,  "I was the anesthesiologist on his team in a couple of surgeries recently."  

Saturday, May 29, 2010

On Dickens

He was almost certainly the best-known man in England in the middle of the nineteenth century, and certainly the most loved: his very personal hold on his readers extended from the most distinguished—Queen Victoria, say—to illiterate workers who clubbed together to buy the weekly or monthly parts in which his novels first appeared so that one marginally literate man could read them aloud to his fellows. And this popularity and influence carried to America, Germany, France, and Russia as well. There was universal sorrow when he died. “I never knew an author’s death to cause such general mourning,” wrote Longfellow. “It is no exaggeration to say that this whole country is stricken with grief.”


Source

Brooksley Born

is one of the few good-guys in Simon Johnson's excellent 13 Bankers about how anti-regulation ideology and financial industry power created the financial crisis.  Simultaneously standing up to Greenspan, Rubin, and Summers took great courage.

Friday, May 28, 2010

Links for 5/28/10

  1. Interview with Emanuel Derman, author of the excellent My Life as a Quant.
  2. Painful profile of a student with too much college debt.  I agree with the author that this is the partly the responsibility of financial aid departments.  I think the primary responsibility lies in the lack of a personal finance course taught at the high school level.  In my opinion it is scandalous that there is not such a course required at every high school in America.  It's as if the schools are preparing a polity ready to be duped by high, variable interest credit card and mortgage companies.
  3. Great artistic video about motivational psychology research.  Open source software is a key example.

Thursday, May 27, 2010

13 Bankers

I’m reading Simon Johnson and James Kwak’s 13 Bankers. It gives a really nice account of the history of banking in the US, highlighting the continual tension between bankers and presidents including Jefferson, Jackson, Theodore Roosevelt and Franklin Roosevelt.

Tuesday, May 25, 2010

Great mouse-free search engine

I've been using Duck Duck Go instead of Google for the last week.  I switched because I almost never need to use the mouse.  I highly recommend it.

http://duckduckgo.com/

Sunday, May 23, 2010

Review

A good trashing of Superfreakonomics.

Writing

A nice passage from Robert Frank's The Economic Naturalist's Field Guide:

Daniel Boorstin, the former Librarian of Congress, used to rise at five o'clock each morning and write for two hours before going into the office.  "I write to discover what I think," he explained.  "After all, the bars aren't open that early."  Boorstin's morning sessions were even more valuable than he realized.  Writing not only clarifies what you already know; it is an astonishingly effective way to learn something new.

Friday, May 21, 2010

Polymorphic recursion workaround in SML

I had something like the following formula type in SML.


type world = int
type param = string
type var = string * int

datatype t = Eq of world * world
           | And of t * t
           | Imp of t * t
           | All of param * t
           | Ex of var * t
           | Hole

There are formulas with holes, and I wanted to fill in a hole with another formula.
Since the fill function does the same thing for the binops and the quantifiers, I
lifted the logic out of the main function (binop and quant)

val fill : t * t -> t option =
 fn (inp, x) =>
   let
      val rec find : t -> t option =
       fn Hole => SOME x
       | And t12 => binop And t12
       | Imp t12 => binop Imp t12
       | All xt => quant All xt
       | Ex xt => quant Ex xt
       | Eq _ => NONE
      and binop: (t * t -> t) -> t * t -> t option =
       fn con => fn (t1, t2) =>
                 case find t1 of
                    SOME t => SOME(con(t, t2))
                  | NONE => Option.map (fn t => con(t1, t)) (find t2)
      and quant: ('a * t -> t) -> 'a * t -> t option =
       fn con => fn (x, t) => Option.map (fn t => con(x, t)) (find t)
   in
      find inp
   end

This didn't typecheck because quant was being called with 'a = var and also 'a = param.
Tom Murphy supplied the pretty workaround: quant gets an extra argument which is 
an abstraction of 'find'.  This breaks the mutual dependency, and shows that the function
is not really polymorphic-recursive.

val fill : t * t -> t option =
 fn (inp, x) =>
   let
      val quant : (t -> t option) -> ('a * t -> t) -> 'a * t -> t option =
       fn find => fn con => fn (x, t) => Option.map (fn t => con(x, t)) (find t)
      val rec find : t -> t option =
       fn Hole => SOME x
       | And t12 => binop And t12
       | Imp t12 => binop Imp t12
       | All xt => quant find All xt
       | Ex xt => quant find Ex xt
       | Eq _ => NONE
      and binop : (t * t -> t) -> t * t -> t option =
          fn con => fn (t1, t2) =>
                      case find t1 of
                         SOME t => SOME(con(t, t2))
                       | NONE => Option.map (fn t => con(t1, t)) (find t2)

   in
      find inp
   end


Nice phantom type example

A nice example of phantom types:  forcing lambda terms to be closed.  
Lifted from an email from Neek Krishnaswami.


type void   (* Empty type *)

type 'a debruijn =  (* Debruijn with nested datatypes *)
 | Var of 'a
 | App of 'a debruijn * 'a debruijn
 | Lam of ('a option) debruijn

let omega : void debruijn =  (* Typechecking ensures omega has no free vars *)
 App(Lam(App(Var None, Var None)), Lam(App(Var None, Var None)))



Note that a free variable, for instance, Var None : void option debruijn.  
Neel used the example to describe a polymorphic recursion workaround in ocaml.


(* Suppose we want a size function...

let rec size = function
 | Var _ -> 1
 | App(e,e') -> 1 + size e + size e'
 | Lam e -> 1 + size e

This won't typecheck, we need polymorphic recursion!
*)

(* Caml allows polymorphic record fields, so declare one with the
polymorphism
  we want in debruijn. *)

type 'b sizerec = {fn: 'a. ('a debruijn -> 'b)}

(* Now we can define a recursive function by going through this record *)

let size =
 let rec s =
   {fn = function
      | Var _ -> 1
      | App(e,e') -> 1 + s.fn e + s.fn e'
      | Lam e -> 1 + s.fn e}
 in
 s.fn

Thursday, May 06, 2010

Lunch with Knuth

I got to have lunch with Don Knuth and Frank and his other students today.  He talked about many things, most interesting to me were the organ and ZDDs.

Tuesday, May 04, 2010

The Economic Naturalist: II

Credit cards in grocery stores.

According to a number of recent articles, e.g.

www.nytimes.com/2009/07/16/business/16fees.html

credit card fees cost stores a large amout of money, thus raising costs to the consumer.  The fees seem to be roughly 2-3% of the cost of the purchase.  While I was waiting in line at Whole Foods yesterday, an economic naturalist question came to mind.  Why don't stores offer discounts for users who pay in cash?  If the discount was less than 3%, this would increase the merchant's profit.

The convenience of credit cards is undeniable.  Lowering the price for cash purchases would give customers an incentive to pay in cash, thus increasing the amount of physical currency the store had to deal with.   This would make the store a better target for robbery, and thus raise the price for armored transport and security guards.  However, I think the main reason high throughput stores like grocery stores don't want cash is that it would also increase the amount of time each person was at the grocery line.  (I'm assuming it takes longer to sort cash and make change than to wait for the credit card authorization.)  Any gain from the cash would most likely be lost by the extra time everyone stands in line.  The longer lines would mean the store would have to spend more on employees to keep lines open, or risk frustrating their customers.

Monday, May 03, 2010

Saturday, May 01, 2010

Thursday, April 29, 2010

Glorious Hack: pretty-mode for Emacs

Today I was lamenting the lack of unicode identifiers and strings in Standard ML.  I asked on the #emacs irc channel how hard it would be to display the string "alpha" as the glyph Î±, for example.  User `jlf' pointed me to pretty-mode for emacs from Arthur Danskin, a student at Johns Hopkins:

www.emacswiki.org/emacs/pretty-mode.el

This is a beautiful hack.  It uses font-lock mode to render strings as other strings rather than just coloring the text in the buffer.  It is easy to add your own unicode characters to display, and the code will compile because only the view is modified.  It's possible to use two different codes for Î±, one for source code identifiers that expands to a legal identifier in the language and another that expands to a unicode sequence that will print as the unicode character.  This is handy for a language like Standard ML (MLton) where unicode is allowed in neither identifiers nor strings.  For instance


val forall =  "\226\136\128"

prints as

val ∀ = "∀"

Sand art

theswedishbed.wordpress.com/2010/04/27/sand-art-a-new-kind-of-land-art/

Wednesday, April 28, 2010

Lazy evaluation for tree replacement in Haskell, OCaml, and SML

(The Haskell code in this post comes from Julia Lawall's paper "Implementing circularity using partial evaluation".  Note also that this post has been significantly rewritten thanks to Jake Donham, a former colleague at both NYU and CMU, who pointed out I didn't know what I was talking about.)

An interesting application of lazy evaluation is to replace all the elements of an int tree by the smallest element without traversing the tree twice.  The pretty Haskell program that does this is:


rm t = fst p
  where p = repmin t (snd p)
        repmin (Tip n) m = (Tip m, n)
        repmin (Fork l r) m = (Fork t1 t2, min m1 m2)
          where (t1, m1) = repmin l m 
                (t2, m2) = repmin r m


We can see this is correct by looking at an invariant of repmin.  Repmin always returns the smallest element of the tree in the second element of the pair, and a tree isomorphic to the first argument filled in with the second argument.  Laziness allows us to provide the minimal value after we've traversed the tree.  Looking at the tree will then give you the correct result.  

In this case laziness provides an elegant solution which would be more cumbersome in SML or Ocaml.  I wondered how much more cumbersome.  I find it difficult to understand the space usage of my Haskell programs, and despite its incredible elegance and advanced features, I prefer Standard ML when my code has to be fast.   I implemented near identical copies of my theorem prover for propositional intuitionistic logic in Haskell and SML.  The Haskell version uses 10X the memory.  Of course, there is a high probability that this is because I'm not a very good Haskell programmer.  Yet the techniques used by experts to achieve good performance can make beautiful code ugly.  I don't think I am alone in this view.  For instance, the Haskell examples at the Programming Languages Shootout are written by experts such as one of the authors of Real World Haskell.  For instance


The programs are laden with strictness annotations and "bang patterns" which basically force the evaluation at the pattern match site.  This suggests to me that often laziness is not the ideal default mode of use.  Here at CMU we teach that laziness is a mode of use of strictness by implementing laziness using closures and references (see below).  However, the example above is beautiful and compelling.  How ugly does it become in strict languages.  Below are some experiments.  If you can do better, I'd be delighted to see your examples.

OCaml

OCaml has some syntactic support for lazy evaluation.  (Note the use of the special syntax `lazy'.)

open Lazy

type 'a tree = Tip of 'a | Fork of 'a tree * 'a tree

let snd (_, y) = y

let rec tmap f t = match t with
  | Tip a -> Tip (f a)
  | Fork (l, r) -> Fork (tmap f l, tmap f r)

let fmap f x = lazy (f (force x))

(* Without type annotations *)
let fm t = 
  let rec repmin t m = 
    match t with
    | Tip n -> (print_int n; print_newline(); (Tip m, n))
    | Fork(l, r) ->
        let (t1, m1) = repmin l m in
        let (t2, m2) = repmin r m in
          (Fork (t1, t2), min m1 m2) in
  let rec p = lazy (repmin t (fmap snd p)) in
    fst (Lazy.force p)

(* With type annotations *)

let fm : int tree -> int t tree =
 fun t ->
    let rec repmin : int tree -> int t -> int t tree * int =
      fun t m -> match t with
        | Tip n -> (print_int n; print_newline(); (Tip m, n))
        | Fork(l, r) ->
            let (t1, m1) = repmin l m in
            let (t2, m2) = repmin r m in
              (Fork (t1, t2), min m1 m2) in
    let rec p = lazy (repmin t (fmap snd p)) in
      fst (Lazy.force p)

let _ = tmap force (fm (Fork(Tip 5, Tip 1)));;

What I like about this code, especially the version with type annotations, is that it is clear that
the second element of the pair returned is strict.   The first version is closer to the Haskell implementation.  It's not so bad except for the need for a special application (`fmap') and the explicit argument to `p'.  

Standard ML

To implement laziness, we need to do it ourselves in SML.  (The SML/NJ compiler has something similar to OCaml's Lazy module, though since my primary compiler is MLton I decided to write it from scratch.)  Update.  This problem is harder than I imagined in the first post.  It seems difficult to solve this problem in SML without resorting to effects apart from the lazy evaluation effects; i.e. making a tree
whose leaves are a ref cell.  There is a rather easy solution using continuations to rebuild the tree once you know the smallest element, but this also traverses the tree twice.  The following solution doesn't work.  


signature LAZY = 
sig
  type 'a t
  val inject_val : 'a -> 'a t
  val force : 'a t -> 'a
  val make : (unit -> 'a) -> 'a t
  val fmap : ('a -> 'b) -> 'a t -> 'b t
  val fmap2 : ('a * 'b -> 'c) -> 'a t * 'b t -> 'c t
  val concat : 'a t t -> 'a t
  val fix : ('a t -> 'a t) -> 'a t
end 

structure Lazy' :> LAZY =
struct 
  datatype 'a laz = Forced of 'a
                  | Thunk of unit -> 'a
  type 'a t = 'a laz ref
  fun inject_val x = ref (Forced x)
  fun force (ref (Forced x)) = x
    | force (l as (ref (Thunk f))) = 
      let
         val x = f ()
      in 
         l := Forced x
       ; x
      end
  fun make f = ref (Thunk f) 
  fun fmap f x = ref (Thunk (fn () => f (force x)))
  fun fmap2 f (x, y) = ref (Thunk (fn () => f (force x, force y)))              
  fun concat x = ref (Thunk (fn () => force (force x)))
  fun fix f = ref (Thunk (fn () => force (f (fix f))))
end

structure L = Lazy'

datatype 'a Tree = Tip of 'a | Fork of 'a Tree * 'a Tree

fun fst (x, y) = x
fun snd (x, y) = y

val fm : int Tree -> int L.t Tree =
 fn t =>
    let
       val rec repmin : int Tree -> int L.t -> (int L.t Tree * int) =
        fn Tip n => (fn m => (print (Int.toString n ^ "\n"); (Tip m, n)))
         | Fork(l, r) => (fn m =>
           let
              val (t1, m1) = repmin l m
              val (t2, m2) = repmin r m
           in
              (Fork(t1, t2), Int.min (m1, m2))
           end)
       val rec p : unit -> int L.t Tree * int =
        fn () => repmin t (L.fmap snd (L.make p))
    in
       fst (p ())
    end

The solution, again due to Jake, is to make a more clever fixpoint operator that makes sure it only is forced once:

signature LAZY = 
sig
  ...
  val fix' : ('a t -> 'a) -> 'a t
end 


structure Lazy' :> LAZY =
struct 
  ...
  fun fix' f =
      let 
        val t = ref (Thunk (fn () => raise (Fail "")))
      in
        t := Thunk (fn () => f t)
      ; t
      end
end


val fm : int Tree -> int L.t Tree =
 fn t =>
    let
       ...
       val p : (int L.t Tree * int) L.t = L.fix' (fn p => repmin t (L.fmap snd p))
    in
      fst (L.force p)
    end




The Economic Naturalist I: A freeway for tourists.

Robert Frank, an economics professor at Cornell, wrote an excellent popular economics book called The Economic Naturalist.  In it he laments the myriad concepts taught in Economics 101, where students are overwhelmed with definitions and facts, yet six months after the end of the course can not solve basic problems in economics.  He fights this trend by asking students to search for counterintuitive economic phenomena in daily life and asks them to describe the phenomena and posit an explanation using fundamental economics principles.  The results are not only entertaining but instructive to the lay person.
Since I am a lay person, I figured I'd try my hand at such an observation.

Instructions:

Your space limit is five hundred words.  Many excellent papers are significantly shorter than that.  Please do not lard your essay with complex terminololgy.  Imagine yourself talking to a relative who has never had a course in economics.  The best papers are the ones that would be clearly intelligible to such a person, and typically these papers do not use any algebra or graphs.

Disclaimer: All comments in the following analysis have a high probability of being at least one of a) uninformed b) unintentionally misleading c) conflate unrelated ideas d) naive e) just false.

A Freeway in Mexico

I noticed a strange phenomenon when I was last in Mexico.  Like many tourists, I visited the stunning Mayan pyramid at Chichen Itza.  I arrived from Tulum, on a small, crowded two lane road.  The trip took approximately 3 hours.  On the way home, I noticed that there was a highway directly back to Cancun, my next destination.  The highway was impressive.  It consisted of between 4 and 6 lanes, and was in better condition than most roads with which I am familiar in the US.  More surprising was that I was nearly the only car on the road.  There were occasional tour busses and other tourists, but Mexican citizens were conspicuously absent.  After the hour and a half it took to reach Cancun, I realized why.  It turned out to be a toll road, and the toll was around $20US.  This angered me at first.  Why should such a resource be used so wastefully, only transporting foreigners able to afford the large toll?  The road could have supported many more drivers with no inconvenience to me.   Clearly an example of an inefficient market.

It was surprising at first, but isn't so much any more.  The function between the cost of the toll and the profit to the private company that ran the road may be maximized at such a high price; lowering the price enough to allow citizens to use the road may generate more fees, but also more road damage.  Moreover, the citizens may be so poor that the company would need to lower the fees so much that even the profits were smaller, regardless of the road damage.  The two-tiered society, say wealthy foreigners and citizens, makes Mexico worse off.  If the discrepancy were smaller, the company could charge less, make as much or more profit, and the economy of Mexico would be considerably strengthened.  Nationalization of the road doesn't seem to solve the problem.  Even if the road became state owned and the charges were lowered, the government would then need to repair the road out of the national budget.  A number of things could then happen.  Either the economy would generate enough new taxes to compensate for the necessary road repairs and Mexico would be better off.  Or it wouldn't and Mexico would be worse off.  The government would have the responsibility for maintaining the road, which would either fall into disrepair or the money would have to be channeled from somewhere else in the budget.  In the short run the people would be better off, but if the road fell into disrepair that improvement would slowly decrease.

One motivation for this sort of road policy may be that it is cheaper to have someone build you a road than to finance the construction yourself.  Perhaps Mexico gave the company an incentive to build the road by giving them toll rights for, say 20 years.  No matter how inequitably they manage the road, at year 20 Mexico has a first-rate road for a modest cost.  This happens in the US.  The city of Pittsburgh, where I live, announced their intention to lease the central turnpike to a company from Spain for a large upfront fee.  This fee would cover some of the state budget deficit, giving the future toll yields to the company for some period of time.

What struck me is that where in a relatively equal society everyone would benefit from a new road, in a highly unequal society, only the wealthy benefit in the short run.

Reversing perspective

3D -> 2D Art

Tuesday, April 27, 2010

GHCi 6.12 unicode emacs problem

I recently installed the Haskell Platform with GHC version 6.12.1 on my Mac.  The primary problem for me has been getting unicode to work correctly.  I was using the utf8-string package, but now it is no longer necessary.  For instance,

main = putStrLn "Ï€ x. p(x)"

works correctly when compiled.  However, I had trouble getting it to work via the emacs interactive buffer.  I found that when creating a ghci buffer with `inferior-haskell-load-file'  my bash shell variables, in particular LC_CTYPE, were not getting set.  I thus created a new program that first sets LC_CTYPE and then calls ghci.  This gets the unicode to print correctly in the inferior buffer.

#!/bin/bash

export LC_CTYPE="en_US.UTF-8"
ghci

I then customize `haskell-program-name' to be the name of this file.  If someone knows a better way to do this, please let me know.

Worth Reading, 4/27

Captives: What really happened during the Israli attacks?,  From The New Yorker 11/9/09

Monday, April 26, 2010

Everybody Draw Mohammed Day

After the odious South Park censorship by Comedy Central, (Ross Douthat wrote a probably accurate, if dramatic, analysis of the mess) an artist in Seattle drew a poster announcing the fictional group Citizens Against Citizens Against Humor that are holding the (formerly) fictional Everybody Draw Mohammed Day.

It caught on with a Facebook page, which quickly exploded with both righteous outrage against threats of violence over free speech, and blatant racism.  While the mean content of the myriad comments is rather low, the best are spot on.


This is not about hate. This is about intimidation. This is not only about Matt and Trey. This is about Salman Rushdie. This is about Kurt Westergaard. This is about Ayaan Hirsi Ali. This is about Sooreh Hera. This is about Theo Van Gogh.
I'm currently a hesitant supporter or the campaign.  Images of the prophet are offensive to Muslims.  I have no desire to offend my Muslim friends and colleagues.  There are other ways to address the actions and rhetoric of the small minority of fundamentalist bullies.  However, in this case I believe that personal action is required.   It is not fair that the writers of South Park be the targets of violence while I am entertained yet share none of their hazard.  Of course, they are rewarded handsomely for their effort, but I am the indirect beneficiary of their exercise of my rights of freedom of speech and expression.  


This collective action is a way to diffuse targets for violence.  Since there are currently only a handful of entertainers willing to take the risk of offending the radicals, they make easy targets for terrorists.  It is unfair that such a burden fall only upon those brave enough to risk violence for free expression.  If we as citizens care about the same ideals, and enjoy the fruits of an uncensored, free society, we should accept some part of the risk.  While Comedy Central has not acted admirably, we can not expect such corporations to take stands against their own financial interest.  If we care about and benefit from freedom of expression and freedom from fear, we should stand up.



Wednesday, March 31, 2010

LaTeX: Nested optional arguments

Latex allows you to make commands with an optional argument.  For example,


\newcommand{\Line}[1][G]{\overline{{#1}}}

Now $\Line$ will draw a G with a line above it, and $\Line[H]$ will draw
an H with a line above.  Nesting these can cause problems though.  For instance,
$\Line[\Line]$ works, but $\Line[\Line[H]]$ doesn't.  The solution is to always
wrap the optional argument in an extra set of curly braces: $\Line[{\Line[H]}]$.


Saturday, March 27, 2010

Why I love John Cheever

We got permission from a swimming instructor and swam across the lake.  We used a clumsy side stroke that still seems more serviceable to me than the overhand that is obligatory these days in those swimming pools where I spend most of my time.  The side stroke is lower class.  I've seen it once in a swimming pool, and when I asked who the swimmer was I was told he was the butler.

from The Jewels of the Cabots

Thursday, March 25, 2010

Tuesday, March 23, 2010

Sunday, March 14, 2010

latex vphantom

In LaTeX you can insert an invisible character, e.g. 'A', by using \vphantom{A}.  This is useful on Beamer slides when you are incrementally uncovering a proof.  Without the phantom letter the proof will wobble as it's uncovered.

Smackdown

From the Pittsburgh parking authority website:


Q. I utilize the Parking Authority metered lots pretty often. I noticed that the signs say, "Head in Parking Only." What is the reason for that?


A. That rule is in accordance with City of Pittsburgh Ordinance #545.03 which states "…All vehicles shall be parked head-in unless otherwise posted…"


Thus, the answer to a good question is "because I said so".   Anyone know what the real reason is?

Tuesday, March 09, 2010

Haskell profiler with -O2

I had a puzzling Haskell experience today.  I was profiling a program and was curious about a function 'new'.  The profiler said it was called 29 times, though I found that hard to believe.   I added a print statement that showed it is called twice.  After being confused for awhile, I finally realized it might be an effect due to the optimizer.  I turned optimizations off (-O2 to -O0) and it went back to 2 calls.  I don't fully understand the so-called Constant Applicative Form (CAF) centers, but I'm still surprised, even with aggressive inlining that it could occur so frequently.  Perhaps it can still count as a call if the inlined body is in a (partially evaluated) thunk.

Thursday, March 04, 2010

Aging

A nice short piece on aging, quoting Longfellow (full poem is here)

What then? Shall we sit idly down and say
The night hath come; it is no longer day?
The night hath not yet come; we are not quite
Cut off from labor by the failing light;
Something remains for us to do or dare;
Even the oldest tree some fruit may bear;
Not Oedipus Coloneus, or Greek Ode,
Or tales of pilgrims that one morning rode
Out of the gateway of the Tabard Inn,
But other something, would we but begin;
For age is opportunity no less
Than youth itself, though in another dress,
And as the evening twilight fades away
The sky is filled with stars, invisible by day.

Monday, March 01, 2010

The Capitol Hill Babysitting Coop

Interesting true story.

http://en.wikipedia.org/wiki/Capitol_Hill_Baby-Sitting_Co-op

 I first read about this in Krugman's Return of Depression Economics.  More
details are here:

http://faculty.wcas.northwestern.edu/~mwitte/B01/handouts/sweeneys.html

Sunday, February 28, 2010

Thursday, February 25, 2010

Mark Twain on risk analysis

Another post blatantly stolen from Schneier.  It's just so funny, and apt since I'm reading a lot about risk for my upcoming job.  His blog is here.


From 1871:
I hunted up statistics, and was amazed to find that after all the glaring newspaper headings concerning railroad disasters, less than three hundred people had really lost their lives by those disasters in the preceding twelve months. The Erie road was set down as the most murderous in the list. It had killed forty-six—or twenty-six, I do not exactly remember which, but I know the number was double that of any other road. But the fact straightway suggested itself that the Erie was an immensely long road, and did more business than any other line in the country; so the double number of killed ceased to be matter for surprise.By further figuring, it appeared that between New York and Rochester the Erie ran eight passenger trains each way every day—sixteen altogether; and carried a daily average of 6,000 persons. That is about a million in six months—the population of New York city. Well, the Erie kills from thirteen to twenty-three persons out of its million in six months; and in the same time 13,000 of New York's million die in their beds! My flesh crept, my hair stood on end. "This is appalling!" I said. "The danger isn't in travelling by rail, but in trusting to those deadly beds. I will never sleep in a bed again."

School laptop spying

This is frightening.  School officials could turn on the laptop camera of school-issued laptops and used this capability to spy on students at home.  (From Bruce Schneier's blog.)

Wednesday, February 24, 2010

My favorite T-shirt logo

Spotted in the Whole Foods parking lot: "It might look like I'm doing nothing, but at the cellular level I'm really quite busy."

A blessing undisguised

I'm reading the latest edition of Strunk and White.  Here are a few nice lines:

* It is an old observation that the best writers sometimes disregard the rules of rhetoric.  When they do so, however, the reader will usually find in the sentence some compensating merit, attained at the cost of the violation.  Unless he is certain of doing as well, he will probably do best to follow the rules.  After he has learned, by their guidance, to write plain English adequate for everyday uses, let him look, for the secrets of style, to the study of the masters of literature.

* All through The Elements of Style one finds evidences of the author's deep sympathy for the reader.  Will felt that the reader was in serious trouble most of the time, a man floundering in a swamp, and that it was the duty of anyone attempting to write English to drain this swamp quickly and get his man up on dry ground, or at least throw him a rope.

* Understanding is that penetrating quality of knowledge that grows from theory, practice, conviction, assertion, error, and humiliation.

Note, in the examples above, that when a sentence is made stronger, it usually becomes shorter. Thus, brevity is a by-product of vigor.


* Transpire.  Not to be used in the sense of "happen," "come to pass."  Many writers so use it (usually when groping toward imagined elegance), ...  


* Avoid the use of qualifiers.  Rather, very, little, pretty---these are the leeches that infest the pond of prose, sucking the blood of words.

Thursday, February 18, 2010

Credit card fees

Interesting article about the perverse economics of credit cards.    The article focuses mostly on the distinction between signature debit and pin debit, but the problem seems to apply to the industry as a whole.  To make the discussion clear, here are some definitions:

1) Consumer = a customer of a merchant (e.g. you or me)
2) Merchant = a customer of both a bank and Visa (e.g. WalMart, etc)
3) Bank = a bank that issues credit and debit cards.
4) Visa = a (publicly traded) company that controls the electronic payment infrastructure (e.g. Visa, Mastercard)
5) Card = a credit or debit card

Some axioms:


1) Merchants, banks and Visa want to make lots of money.
2) When a consumer uses a card at a merchant's store, the merchant must pay two fees.
  a) a small fee to use the Visa network (about 5 cents)
  b) a large fee to the consumer's bank, (about 1-3% of the purchase price)
  Visa sets both fees (a) and (b)
3) Visa does not issue cards.   Only banks do that.


Now for some simple inference.

By (1), merchants want low fees, banks want high fees.  By (1) and (2) Visa wants as many consumers
using Visa cards as possible.  By (3) Visa's customers are really the banks, not the consumers.  Visa wants banks to issue more Visa cards.  Therefore, Visa has an incentive to raise their fees, thus attracting banks that want to make those higher fees.

Visa can't set the fees too high or merchants will revolt and refuse to accept cards.  But now Visa and Mastercard are in some kind of reverse competition: who can set their rates the highest without a revolt from merchants.

If this were a free market, one could imagine creating a new Visa-like company (with the associated infrastructure) and drop the bank fee to cover the cost to the banks of supplying the cards.  Here the consumers and merchants benefit from the competition, rather than the banks and Visa.   Unfortunately, the card must be attached somehow to the bank account, and only the bank can do that.  So it seems there is a big problem with this market.  Perhaps this could be circumvented in the future if everyone has a PayPal-like account and all the transactions take place directly over the internet.  I can imagine some kind of authentication device being used, part of a phone say.  Merchants could give a small discount to use the PayPal (non-Visa) system.  The banks could fight this of course, but it seems like a possibility for the future.

Emacs word search

One nice feature of Emacs for editing TeX documents is called word-search.  When you're looking at your typeset document and want to go to a particular place, you can simply do a search for the text around the location.  Unfortunately, you don't know where the line breaks are in the file, and thus this simple strategy will fail.  If you use word-search-forward (or C-s RET C-w WORDS) Emacs will build a regular expression that ignores both space and punctuation and go to the correct spot.  

For example, if the pdf file says

The quick brown fox, jumped over the lazy dog.

but the text file has

The quick brown
fox,
jumped
over the lazy dog.

and you word-search for

"brown fox jumped"

it will jump to the right spot.

Tuesday, February 16, 2010

Typo rant

In this article from the most important newspaper in Indiana, there are two typos in three adjacent words.  Do they even use spellcheckers in journalism anymore?  I've noticed a number of typos on the NY times website recently, but this one takes first prize.
"D’Ippolito needed 500 signaures of registerd voters in each of Indiana’s nine congressional districts."
I wonder if non-profit organizations like ProPublica will be able to take care of these dinosaurs.

Verizon

This is clearly one of the companies people mean when they rail against large corporations.  I cancelled my service last month to switch to ATT.  Because I cancelled on Jan 15, but my "cycle" began on Jan 12 I was charged a full month of fees.  They're just evil.  As more evidence, a whistleblower recently gave the New York Times damning evidence about how they deliberately design their phones so it's easy to get overcharged by accidentally accessing the internet.  As usual in the US, caveat emptor.

Monday, February 01, 2010

Toyota acceleration

I've been reading about new Toyotas accelerating out of control and killing everyone inside.  (Imagine that the car just starts accelerating and you can do nothing to stop the acceleration.)  I was imagining how scary it must be, and what you're suppose to do when it happens.   Here are the best ideas I've seen.
  1. Turn the engine off.  
  2. Put the car in neutral.
It's obviously hard to remember this when it's happening.  Solution 1 is a bit scary since you would lose your power breaks and power steering.  If you're going fast the steering wouldn't be a big deal, but I'd be nervous about the breaks.  Is there even a physical connection between the break pedal and the actual breaks in modern vehicles?    Solution 1 is problematic for new cars with keyless ignition.  

Solution 2 will destroy your engine, but not you.  A benefit of a manual transmission is that it is easy.  In fact, just push the clutch in.  I'm not sure if it's always possible with an automatic.  I know on my mom's accord there is a locking mechanism to keep you from putting it in reverse when you're moving forward, but I don't think it applies to neutral.  It seems low-tech cars are the way to go.  One reason to stick with my  1998 Civic.  

Monday, January 25, 2010

Gripping article about John Paul Stevens and today's court

http://www.nytimes.com/2010/01/26/us/26bar.html?hp

Highlight:

Thursday’s decision in the Citizens United case was more full-throated.
“The majority blazes through our precedents,” he wrote, “overruling or disavowing a body of case law” that included seven decisions.
Justice Stevens, who served in the Navy during World War II, reached back to those days to show the depth of his outrage at the majority’s conclusion that the government may not make legal distinctions based on whether a corporation or a person was doing the speaking.
“Such an assumption,” he wrote, “would have accorded the propaganda broadcasts to our troops by ‘Tokyo Rose’ during World War II the same protection as speech by Allied commanders.”
The reference to Tokyo Rose was probably lost on many of Justice Steven’s readers. But the concluding sentence of what may be his last major dissent could not have been clearer.
“While American democracy is imperfect,” he wrote, “few outside the majority of this court would have thought its flaws included a dearth of corporate money in politics.”

Sunday, January 24, 2010

Whale Rescue

This is amazing.  Listen to the latest RadioLab, "Animal Minds" where they talk about the daring rescue of a humpback whale in San Francisco:

http://blogs.wnyc.org/radiolab/2010/01/12/animal-minds/

Here is video:

http://www.youtube.com/watch?v=G9fVEz5d4HU

Wow

The power of half.

Thursday, January 21, 2010

Fringe mode in Emacs

My latest Emacs update added an annoying property whereby the space in a buffer after the EOF marker had dots on the left to show me that the file had ended.  Thus, in a one line file, I'd open it and see the one line, and 100 lines of dots on the left margin.  Really annoying.  The problem is it's hard to figure out how to turn it off.  I googled "emacs dots eof", but I got nothing but "dot-emacs" sites.  I asked on the excellent #emacs IRC channel, and some kind soul (shabble) pointed out it's called "fringe-mode".  You can turn it off with (fringe-mode 'none).

Wednesday, January 20, 2010

The Inverse Method for the Simulation of Consciousness?

This paper has a great title.  I wish I had such confidence in the inverse method.  It may make working on my thesis a more exciting prospect.

Saturday, January 16, 2010

Antiaging

The antiaging debate is on. 



Interesting passages:

Comite left a tenure-track position at Yale because she became
frustrated with what she saw as medicine’s red tape and tunnel vision.
One galvanizing moment involved a woman named Vivian, who had a badly
scarred uterus and who had tried repeated in vitro fertilizations
without success. She came to see Comite at Yale, still hoping to have
a child, but failed to conceive. At wit’s end, Vivian consulted an
acupuncturist. She became pregnant after only a few treatments.  “I
would swear on a stack of Bibles and all my oaths there was no way
that woman could conceive,” Comite says. “That experience turned me
into an open-minded skeptic.”


Every year, Life gets a new set of beefcake photos taken. Now 71, he
said he put on five pounds of muscle this past year by scheduling
extra tae kwon do practices and cranking it up a notch in the weight
room. He can bench-press 235 pounds and can do 10 pull-ups, “full
extension.”  His age-management program could fill a spreadsheet. Life
began reciting from memory: 1,000 milligrams of calcium daily,
coenzyme Q10 pills twice a day, 5,000 units of vitamin D, 4 grams of
fish oil, 10 milligrams of melatonin at bedtime, a testosterone
injection once a week, human-growth hormone once a day. “That reminds
me,” he said, reaching into his desk drawer. “I’ve got to give myself
a shot.”  He pulled out a syringe, loaded up on human-growth hormone,
raised a pants leg and stuck the needle into his left thigh.



Tuesday, January 12, 2010

Unicode in an Emacs shell

My current project is a Haskell program that generates a lot of unicode that gets dumped to the screen.  I occasionally need to sift through the output. My usual method is to run a terminal in an emacs buffer (via M-x shell) and run the command line program generated from Haskell through that shell.

I was recently frustrated when I updated from Emacs 22 to Emacs 23.  While the unicode support is much better in general in Emacs 23, the shell stopped printing the unicode correctly.  After lots of false starts, I finally found that you need to run the following command:

M-x set-buffer-process-coding-system
with mule-utf-8 for both input and output.  Or add

(set-buffer-process-coding-system 'mule-utf-8 'mule-utf-8)

to the shell-mode-hook.  Then the unicode prints correctly.