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.

Tuesday, December 22, 2009

HP computers are racist

This is unbelievable!  The face recognition software on HP computers will track a white face, but not a black one.

Saturday, December 19, 2009

The bus comes for those who wait.

Carmen Herrera sold her first painting in 2004 at age 89.  Now she's a super star.

Tuesday, December 15, 2009

Tuesday, December 08, 2009

Tuesday, December 01, 2009

Inspirational

I hadn't heard of Ida Tarbell until I read Simon Johnson's nice rebuttal of an argument I've found persuasive in the past.

The Pinker-Gladwell debate is entertaining

Stephen Pinker and Malcolm Gladwell have been going at it over predictors of success, such as IQ score and a football player's place in the draft.

A surprising fact

Benford's Law

Tuesday, November 24, 2009

Poignant story about a runaway with Aspbergers.

Saturday, November 21, 2009

Wednesday, November 18, 2009

11/18/09

  • More pirates.  
    • Interesting point:  "In the attack, the Alabama's crew also took evasive maneuvers and used a new technique to repel pirates: a so-called long-range acoustic device, which emits high-pitched sounds painful to the human ear."  
  • Psychology in the subway.  Some interesting tidbits. 
    • "The more justification that was offered, however, the less likely people were to stand up."
    • "Incidental touching was more likely to occur among same-race, same-sex passengers."

Friday, November 06, 2009

Links for 11/6/09

Good QuickCheck tutorial

Profiling + Template Haskell + Cabal

Cabal makes building, installing and distributing a Haskell program very easy.  Template Haskell makes writing cool pattern matching easy.  Profiling makes, well profiling easy.  But how can you do all these things together?  TH doesn't work well with profiling, so you need to compile twice.  Once with no profiling to make regular .hi and .o files.  Then again with profiling, renaming the .o and .hi files to .o_p and .hi_p in order to make it work.  With Cabal, you can basically do the same thing.  Compile once without profiling

runhaskell Setup.lhs configure --user
runhaskell Setup.lhs build
runhaskell Setup.lhs install

then again with the following additions to your cabal file, in the ghc-options section:


-prof
-auto-all
-osuf p_o
-hisuf p_hi

This should build the TH project with profiling support.

Sunday, November 01, 2009

Quotes for 11/1/09

  • He’s highly educated – and rather better than a country like this deserves.  -- Gore Vidal on Barack Obama
  • God looks after alcoholics, little children, and the United States of America. -- Otto von Bismarck
  • "I wish you and your family also as to your friend Merry Christmas and a happy New Year and I hope that we'll meet again in a world of peace and freedom in the taxi cab if the accident will."    I like that very much: "If the accident will."  -- Kurt Vonnegut, Slaughterhouse Five
  • "The Dresden atrocity, tremendously expensive and meticulously planned, was so meaningless, finally, that only one person on the entire planet got any benefit from it. I am that person. I wrote this book, which earned a lot of money for me and made my reputation, such as it is. One way or another, I got two or three dollars for every person killed. Some business I'm in." -ibid



Links for 11/1/09

Good op-ed by a rancher against meat demonization.  He reiterates Michael Pollan's point that grass fed, organically grown beef has low environmental impact.  Far lower than, say, Brazilian soybeans.

Fact about Incendiary bonbs:
Modern incendiary bombs usually contain thermite, made from aluminium and ferric oxide. The most effective formula is 25% aluminium and 75% iron oxide. It takes very high temperatures to ignite, but when alight, it can burn through solid steel. In WWII, such devices were employed in incendiary grenades to burn through heavy armor plate, or as a quick welding mechanism to destroy artillery and other complex machined weapons.

Saturday, October 31, 2009

Quotes for 10/31/09

"Everything reminds Milton Friedman of the money supply. Everything reminds me of sex, but I try to keep it out of my papers." - Robert Solow

Friday, October 30, 2009

Siege of Leningrad

Siege of Leningrad.  Pointed out in the Yale food course in the lecture on starvation.  In the rationing, manual laborers were given about 700 calories per day.  Non-manual laborers around 400.   Citizens recalled that the paste to put up wallpaper was made of potatoes.  Wallpaper was stripped off walls, and the dry paste was scraped into pots and boiled into soup.  Leather as well.  This was by the end of the first year.  The siege lasted another 1.5 years.  Then the cannibalism began.  After the corpses were eaten, children began disappearing.  The government made it illegal to sell fresh meat.  Over 1 million deaths by starvation.  1.5-3 million overall.  After the siege was lifted, it was formally illegal to speak of the cannibalism that took place during the siege.

Articles for 10/30/09

  1. Interesting Wal-Mart hack.  How can personal information be so poorly protected by such a massive store?
  2. Draw a symbol, and get the LaTeX code back.

Thursday, October 29, 2009

Blue footed bubi

Who knew?









Richmond rape case

The recent Richmond High School rape case (article 2) has a number of disturbing qualities.  The short story is that a 15 year old girl left a dance at the school, met up with some people on the side of campus, and was brutally raped by 6-10 young men, while the whole incident was observed by something like a dozen other people. Particularly important is that no one at the scene called the police, and the grisly mess lasted for nearly 2 hours.

In addition to the facts of the case, a number of comments also grabbed my attention.  The perpetrators currently in custody are aged 21, 19, 17, 16, and 15 years old.  The 21 year old has not been charged yet as far as I know.  The 19 year old is apparently the main assailant.  The DA apparently will seek life in prison for him, as well as for the juveniles (to be tried as adults).  An investigator from the police department is quoted as saying
  "These suspects are monsters. And, I don't understand how this many people capable of such atrocious behavior could be in one place at one time."
Focusing on the non-participating witnesses first, the first thing that's been on my mind regarding this case is the seemingly similar case of Kitty Genovese
that will be well known to anyone who took Psychology 101.  There a woman was beaten to death in broad daylight on a busy New York City street.  Similarly, no one watching the violence escalate called the police.   After the initial name calling and sermons on how NYC is a den of thieves, psychologists went around asking witnesses why they didn't call the police.   They replied that they figured someone else had already called them.  This led to numerous studies on group behavior that corroborated the claims.  It's one of the reasons I think Psychology 101 is the most important courses in college:  If you are aware of your tendency, as a human being, not to act in group situations, you can overcome your natural response, and get something done.

This seems slightly different though, since due to the remote location, any witness could see what any other witness was doing, so it would probably be clear if someone had called the police or not.  I'm curious whether there were threats of physical violence to the crowd from the attackers if anyone alerted the police, or if it was something like a Roman Colosseum spectacle.  In Gangleader for a Day, minorities from the Robert Taylor homes just don't call the police, since the police are frequently abusive and infrequently get anything done there.  Perhaps something like this was at work.

The second thing that sticks in my mind is the immediate response of the DA that he will not only seek to try the minors as adults, but will seek life in prison for all 4.  Even the oldest (currently charged), at 19,
is depressingly young.  Now, I'd agree that they obviously pose a danger to society, and should spend time in prison.  But a 15 year old getting life?  It is possible that he is a young psychopath that will do nothing but rape and pillage as long as he's on the streets.   Yet I find that incredibly hard to believe.  The interesting thing to me is the quote.  Again
  "These suspects are monsters. And, I don't understand how this many people capable of such atrocious behavior could be in one place at one time."
Indeed.  It seems highly improbable that 6-10 sociopaths happen all to go to the same high school and happen to all be hanging out together after a dance.   (Though, on second thought, any gang would probably satisfy this description.)  I think it is important to figure out what was going on in their minds (e.g. peer pressure) while this was happening.  The fact that the area is impoverished and known for gang violence, also would seem to play some kind of role.  I hope the psychology department at Berkeley researches this crime as seriously as those researchers studying the Genovese case.

In Stumbling on Happiness, Dan Gilbert reports on research showing that, almost unbelievably, about half of the people involved in horribly traumatic experiences similar to this one (though indeed this must be near the top of the list of most horrendous crimes) are able to recover psychology from the trauma.  I pray that the victim of this tragedy is one of these resilient ones.

Tuesday, October 27, 2009

Supertasters

I'm listening to the new food course from Yale online.  The most interesting fact so far is the existence of supertasters.  Basically, some people react to tastes much more strongly than others.  For instance, a supertaster might experience broccoli as extremely bitter.  I'm constantly amazed when people don't like things like olives or avocados.  Perhaps if I could experience their presumable super-reaction I'd dislike them as well.

Outrun a horse?

Is this true?  From http://www.nytimes.com/2009/10/27/health/27well.html?em  Seems impossible to me.
Most mammals can sprint faster than humans — having four legs gives them the advantage. But when it comes to long distances, humans can outrun almost any animal. Because we cool by sweating rather than panting, we can stay cool at speeds and distances that would overheat other animals. On a hot day, the two scientists wrote, a human could even outrun a horse in a 26.2-mile marathon.

Sunday, October 25, 2009

Cool hack

http://en.wikipedia.org/wiki/Xor_linked_list

Efficiency

I ran into a friend coming out of the grocery store last night.  In mock surprise, I said "What are you doing grocery shopping on Saturday night?".  She replied, "Well, if I go on Sunday morning I spend so long shopping.  On Saturday night, well, it's sad to be grocery shopping, so I get done quickly."

Friday, October 23, 2009

Oil Creek State Park

The most undervalued park in western PA.  A perfect place for a short weekend backpacking trip.

Funny rant on SFO travel.

So true. Public transportation to SFO is bad.

puzzles

Article on Martin Gardner, the math puzzle guy.

Wednesday, October 21, 2009

Monday, October 19, 2009

Against Transparency

Article by Lawrence Lessig on the surprising downside of donation transparency in government.

Wednesday, October 14, 2009

Best PL quote I've heard since CADE.

This one also involves Derek Dreyer.

http://www.iai.uni-bonn.de/~ralf/WG2.8/24/slides/derek.pdf

"Great, but who cares about the Apply functor?  It's a very lame functor."

Tuesday, October 13, 2009

Monday, October 12, 2009

Death penalty

I'm not against the death penalty in principle.  In practice though, it's usually impossible to
know for sure if the guy is guilty.  At least if you imprison a guilty person, you can let him
out when you realize your mistake (and the governor doesn't interfere with the case).
This simple fact and the further fact that executing someone actually costs more than keeping
them in prison for life makes the death penalty seem completely wrongheaded.

http://www.newyorker.com/reporting/2009/09/07/090907fa_fact_grann/

Sunday, October 11, 2009

Weird Haskell import behavior

Say you have a module A:

module A where

class A a where
  a :: a -> a

Now you wish to write a module B that instantiates A.A.
Since you don't want to include the whole namespace of A, you try

module B where

import A(A)

instance A Int where
  a = id

This fails to compile because it says 'a' is not a visible method of class A.  The strange thing is it compiles if you instead write

module B where

import qualified A
import A(A)

instance A Int where
  a = id


I find this strange since you don't have to write

instance A Int where
  A.a = id

Importing with brackets brings only those names into scope, thus making a not
visible.  But I fail to see why importing all of A qualified allows you to figure
out that a (unqualified) is visible.

A good article day

Great article about the celebrity chef Jamie Oliver, and his crusade in America.

Another good one by Malcolm Gladwell comparing dog fighting and football injuries.

Thursday, October 08, 2009

Haskell strictness

The following Haskell program eats 2GB of memory in about 5 seconds:

index n i (x:xs) = if x == n then i else index n (i+1) xs
main = putStrLn $ show $ index 0 0 [1..]

This seemed odd to me, since it is tail recursive.  The problem is that the i+1 does not get evaluated, and therefore creates a thunk at each recursion step.  Compiling with -O2 fixes this, as does the following fix

index n i (x:xs) = i `seq` if x == n then i else index n (i+1) xs
main = putStrLn $ show $ index 0 0 [1..]

This simple example just shows how you really have to unlearn your most fundamental strict functional  programming beliefs if you start hacking Haskell.

Good column on health care by Nicholas Kristof

Tuesday, October 06, 2009

A dissenting opinion on electronic voting.

M. Shamos at CMU is the first computer scientist I've seen argue that paper trails are a bad idea in electronic voting.  I don't agree with his biggest point, but I think that there is some interesting
sociological information there.  For example, requiring paper trails by law stifles technological
innovation since anything non-paper-based would be illegal.

Monday, October 05, 2009

Cabal oddity

When you use Cabal to make a library, you have to be careful about what you include in the 'exposed-modules' section.  If you don't include a module, and you refer to it in another library, the code will compile, but not link.  It will give you an uninformative (ar) error message about undefined symbols.
This will even happen if you export modules that use unexported modules.  I think of this as a bug,
but for now, I suggest exporting every module that might be touched by an export.

Excellent article about Larry Summers

http://www.newyorker.com/reporting/2009/10/12/091012fa_fact_lizza?currentPage=all

Thursday, October 01, 2009

Best GHC option

-B:
Sound the bell at the start of each (major) garbage collection. Oddly enough, people really do use this option! Our pal in Durham (England), Paul Callaghan, writes: “Some people here use it for a variety of purposes—honestly!—e.g., confirmation that the code/machine is doing something, infinite loop detection, gauging cost of recently added code. Certain people can even tell what stage [the program] is in by the beep pattern. But the major use is for annoying others in the same office…”