Erlang: Danger of Mixing Records and Tuples

November 13, 2011

I received an error from the erlang compiler: “Warning: this clause cannot match because a previous clause at line 387 always matches” and was staring at the code trying to figure out why the top clause was a ‘catch all’.

case Result of
    {Version, NewId, ConnectionStates, NextProtocol} ->
        ....
    #alert{} = Alert ->
        ....

so #alert has 3 fields so is always matched by the 4 field tuple. :(

Compiler CPS Transformations

September 3, 2011

It looks like people are now writing compilers to deal with node js spaghetti callback code. These are available for C#, Javascript (useable with nodejs) and Scala.

C# 5.0

C# 5.0 will have await/async keywords

http://msmvps.com/blogs/jon_skeet/archive/2011/05/08/eduasync-part-1-introduction.aspx

you can write non-blocking http handler like:

public async void get(Request request, Response response) {
  var json = await Redis.get(request.getParam("id"));
  await response.write(json);
}

Redis#get and Reponse#write are both async methods

if you need to do parallel handling:

public async void get(Request request, Response response) {
  var json1Task = Redis.get(request.getParam("id"));
  var json2Task = Redis.get(request.getParam("id"));

  await response.write(await json1Task + await json2Task);
}

Scala

Scala has continuations using the shift/reset keywords which seems to be much harder to grock than await/async.

http://www.scala-lang.org/node/2096

However, if you wrote a proper non-blocking library you would probably never use shift/reset in client code. it would all be in the library. if you have a shift which is not nested in a reset then the method becomes CPS and if you have a method that calls a CPS method it becomes CPS as well. it spreads a bit like a virus infecting everything it touches. so it is mostly transparent.

you can write non-blocking http handler like:

def get (request: Request, response: Response) = {
  val json = Redis.get(request.getParam("id"))
  response.write(json)
}

#get, Redis#get and Reponse#write are all CPS.

if you need to do parallel handling then:

def get (request: Request, response: Response) = {
  val json1Future = Redis.getAsync(request.getParam("id1"))
  val json2Future = Redis.getAsync(request.getParam("id2"))

  response.write(json1Future.await, json2Future.await)
}

here Future#await, #get and Response#write are CPS. Redis#getAsync is a normal method that returns a Future that has a CPS await method.

the main difference between c# and scala is in c# the caller is able to choose whether they want to (appear to) block on an async method while in scala the callee has to expose a blocking and a non-blocking version of the method. It appears to be possible to create a function that convert a CPS blocking method to a method that returns a Future. I have some code that does it for 1/arity methods. https://gist.github.com/1191571 I suspect that there is a much simpler way of doing it but I don’t understand scala continuations enough to work it out :)

Javascript

For javascript there are many options

Streamline JS (https://github.com/Sage/streamlinejs) has been written specifically for nodejs.

You can write a non-blocking http handler like so:

function get(request, response, _) {
  var json = Redis.get(request.getParam("id"), _);
  response.write(json, _);
}

which compiles to:

function get(request, response, _) {
  var json;
  var __frame = {
    name: "get",
    line: 1
  };
  return __func(_, this, arguments, get, 2, __frame, function __$get() {
    return Redis.get(request.getParam("id"), __cb(_, __frame, 1, 13, function ___(__0, __1) {
      json = __1;
      return response.write(json, __cb(_, __frame, 2, 2, _));
    }));
  });
};

There is also TameJS which doesn’t have magical error handling:

https://github.com/maxtaco/tamejs

You can write a non-blocking http handler like so:

function get(request, response) {
  await {Redis.get(request.getParam("id"), defer(var err, var json))};
  // error handling cut out
  await {response.write(json, defer(var err))};
  // error handling cut out
}

There is also:
Narrative JS (http://www.neilmix.com/narrativejs/doc/example.html)
Stratify JS (http://onilabs.com/stratifiedjs)

and there was an attempt to get a defer keyword added to coffee script

https://github.com/jashkenas/coffee-script/issues/350

My First Firefox Addon

November 1, 2010

Javascript Deminifier

Sometimes I want to debug some javascript in firebug but it is minified which makes it really hard to put breakpoints in because all the code is on the same line. This plugin deminifies javascript as it is downloaded. However, it does rely on the javascript being served with the proper mime type. There are some functions in firefox that let you access the pretty printed version of javascript functions and another plugin javascript deobfuscator uses this. But you can’t see the deobfuscated code in firebug. :(

Socialist Alliance?

August 21, 2010

Trog’s vote-a-matic recommends I vote Socialist Alliance in the Australian election. Unfortunately, for the Socialist Alliance the vote-a-matic is slightly rigged. The vote-a-matic identifies each party as either supporting, opposing or being neutral towards a statement. If your response matches the parties response and is not neutral then this counts as a tick for that party. The party with the most ticks is the recommended party. However, this is biased towards the Socialist Alliance and the Greens because they have the lowest number of neutral responses (19/26) compared to the highest from the Australian Sex Party (67). Oppose or Support weakly dominates the neutral response. If you chose neutral you could always do the same or better by choosing oppose or supports. So a party that has a lot of Oppose/Support responses is most likely to come out on top.

Oppose Support Neutral
Oppose +1 0 0
Support 0 +1 0
Neutral 0 0 0

That row of zeroes for neutral is not where you want to be :)

Self Checkouts

August 20, 2010

Self checkouts = optimal form of retail price discrimination. Surely, you can shave 5% by being dishonest. My future prediction: stores abandon loyalty cards when they realise self checkout performs the same function.

Edit: forgot to add my rant about how 90% of the time I have to pack my own bags in the uk compared to never in aus. Thank god for Australian checkout chicks ^w workers.

Ansi QrCodes in Ruby

June 23, 2010

Linux lets you change the foreground and background colors of the terminal. You can use this to create QR codes.

#!/usr/bin/ruby -w
require 'rubygems'
require 'rqrcode'

margin = 1
qr = RQRCode::QRCode.new(ARGV[0], :size => 4, :level => :h )
res = ""

size = qr.modules.size + margin * 2
white = "33[5;37;47m  "
black = "33[0;34;40m  "
size.times do |x|
  size.times do |y|
    if x < margin || y < margin || x >= size - margin || y >= size - margin
      res += white
    elsif qr.is_dark(x - margin,y - margin)
      res += black
    else
      res += white
    end
  end
  res += "33[0m\n"
end
puts res


Google maps rant

June 17, 2010

I would prefer to know where I need to go rather than where I’m going

Life is rigged

June 16, 2010

Why does google maps keep giving me us addresses. Eughhhhhhh!! Waterloo, uk should give me a uk address.

No Escaping Retributivist Reasoning

June 13, 2010

Quote from my new favourite law paper discussing ideas I raised in death penalty conspiracies and lotteries:

But, retributivists claim, whether or not this is a good idea does not depend on the balance of costs and benefits. It is simply wrong to kill someone for double parking. A related problem is that of punishing the innocent. It is possible that, under certain circumstances, falsely convicting an innocent person would have a salutary deterrent effect, enough to justify that person’s suffering, etc. Critics also note that, so far as deterrence is concerned, it is the threat of punishment that is justified and not the punishment itself. Thus, consequentialism might justify letting murderers and rapists off the hook so long as their punishment could be convincingly faked.

The standard consequentialist response to these charges is that such concerns have no place in the real world. They
say, for example, that the idea of imposing the death penalty for parking violations to make society an overall happier place is absurd. People everywhere would live in mortal fear of bureaucratic errors, and so on. Likewise, a legal system that deliberately convicted innocent people and/or secretly refrained from punishing guilty ones would require a kind of systematic deception that would lead inevitably to corruption and that could never survive in a free society.

Retributivist intituions are so strong that consequentialists have to make arguments as to why better social equilibriums are not possible. If we could have convincing fake punishment the world would be better off. However, unfortunately it is probably not possible.

And who would have thought Jesus or Buddah would have such a good  understanding of neurobiology and determinism:

Intuitively, we want to punish those people who truly deserve it, but whenever the causes of someone’s bad behaviour are made sufficiently vivid, we no longer see that person as truly deserving of punishment. This insight is expressed by the old French proverb: ‘to know all is to forgive all’. It is also expressed in the teachings of religious figures, such as Jesus and Buddha, who preach a message of universal compassion.

There is something beautiful about universal compassion and forgiveness being tied to materialistic determinism.

Lessons Learned

May 14, 2010

* checking the station signs is cheap compared to getting stuck in new eltham

* there is a plant similar to lantana in england and i’m now very itchy

* there is a road block around new eltham staffed by around 6 females. they charge 50p for passing. 50p is a fair price for passing.


Follow

Get every new post delivered to your Inbox.