Sunday, December 1, 2024

The case for Subtypes: real world and programming

Subtyping fits naturally with our human view of reality. Consider these sets of individuals: Dogs, Cats, Humans, Crocodiles, Mammals, Quadrupeds, Animals. There is a natural relation between them represented by this diagram:

At a simple level these are just sets of individuals and the arrows represent set inclusion. But clearly there is more to it than that. The Dog type is distinguished by properties that let us identify an individual as being a dog. And we can see that there is a symmetry in the diagram. As we go up we get more and more individuals in the type, but as we go down we get more and more properties.

This perfectly natural form of subtyping is the right way to do subtyping in a computer programming language.

Now imagine a box that always has a dog in it, and we can change the dog inside to any other dog. Nobody would think that the type of such boxes was a subtype of boxes that have a mammal in it and we can change the contents to any other mammal. The mammal box isn't a dog box because it might have a non-dog inside, and a dog box isn't a mammal box because it isn't big enough for all mammals. They are just different.

Computer memory is like those boxes. Consider 16 bit integers. They can be naturally seen as a subtype of 32 bit integers, since every such can be represented in 32 bits, and 16 bit integers have the property that the integer fits in 16 bits. We can look at a 32 bit integer and decide if it fits in 16 bits. Now consider memory locations that have enough space for a 16 bit integer. These can't be used if what you want is a memory location that can hold a 32 bit integer. And the reverse is equally true: if you have a memory location with a 32 bit integer in it, then you can't use it where you expect a memory location with a 16 bit integer. Once again, they're just different.

Because computers work with changeable memory locations, many programming languages conflate values, such as integers, with boxes which can hold such a value. The first object oriented programming language was Simula 67 and it had classes that consisted of multiple memory-like boxes. It had subclasses which were a brilliant innovation, but they didn't work as we naturally expect, and that has been leading programmers astray, causing bugs, ever since.

Functional programming style emphasizes values rather than places for changing values. These value types naturally form a subtyping hierarchy that behaves the way humans expect. And it turns out that if you organise your type hierarchy correctly a lot of magical goodness results. 

The rest of this post will get more technical, and belongs in my programming blog (https://wombatlang.blogspot.com/) where it will also be posted.

Tuesday, October 29, 2024

Squeezes strike twice in the round of 16

In the round of 16 in the Open World Bridge Championship, Romania trailed China by 5 going into the last set of 15 boards, but lost by 34. I had a look to see what happened and 2 hands stood out. Note that I am only guessing about how the play went -- I can only see the result and the lead.

First a quiz:

1. You are declarer in 5S looking at:

♠ A K Q 3
 A K Q 6 4
 A 6
♣ Q 3

♠ J 9 7 4 2
 J 7
 Q 9 5 4
♣ J 2

The  defenders cash the AK of clubs and exit with a heart to your J. Plan the play.

2. You hold:

♠ J 9 4
 J 4
 Q 8 6 5 4 3
♣ 8 4

The opposition are in 6S, and you are sure from the auction that declarer has 5 spades to the AK. Do you lead a spade? Which one?

Saturday, August 31, 2024

Mixed Individual Bridge

There are team competitions and mixed teams, there are pairs and mixed pairs, there are individuals and ... Well, before we get to that, an aside.

Young people are struggling today. The Internet provides alternatives to personal connections that are compelling but leave people anxious and unable to get on with life. When I was young, long ago, I struggled with life, and I was saved by getting involved with Bridge. I married a Bridge player, and conversations about the game have been a nice aspect of our life that has never become boring after more than 50 years. Bridge seems to hit a sweet spot combining skills, co-operation, competition, uncertainty and the vicissitudes of good and bad luck. Perhaps  a resurgence in our game could play a part in fixing the world's current malaise.

When I started there was a natural progression from simpler trick-taking games to rubber bridge to tournament bridge. This doesn't work nearly as well in the Internet age. Maybe Mixed Individual Bridge can be part of a different progression. Let's think about it.

The concept is actually very simple. We divide the field into two equal sets, which we suggestively label M and F. We then play a partial individual movement, but the M players are only North and West, and the F players are only East and South. There are then two results: one for the M players and one for the F players.

A two table match is the most convenient for some purposes. This has four M and four F players. We want each M player to partner each F player an equal number of times. We also want each M player to compare against each of the three other M players an equal number of times. So there has to be a multiple of 4 times 3 equals 12 rounds. It is also possible to do a 3 table mixed individual movement over 12 rounds with some imbalance, which might be convenient when the total number of tables is odd.

While a mixed individual will suit many, others would prefer non-mixed. And this will be necessary if there is an excess of M or of F players. This can be run the same way with an arbitrary or seeded split into North-West and East-South halves with separate winners. This allows these to be run alongside mixed competition.

I think it works best to run short matches of just 12 boards over 90 minutes or so. Then, if there is time for multiple such matches, there can be a swiss-style assignment of players to matches, with players finding their own level. Indeed I think it is possible to run a continuously updated ranking system in the style of that used in professional tennis, with people moving up when they finish ahead of those ranked higher. One would need to smooth the volatility, since this form of play will have a higher element of luck than we expect in pairs and teams competitions.

An essential feature to make this plan work is that there should be a fixed simple bidding system used by all. There is then no need for explanations or alerts. This also applies to leads and signals. The complexity of the prescribed system may vary with the players' level. At the lower levels the system should exclude all weak artificial bids, and psyching strong artificial bids should be forbidden.

For a beginner's level, the hands should come with a predefined auction, together with an explanation of the bids in that auction. So then the game is just about the play of the cards, but with the information that an auction can provide.

I think this could become a new progression leading into the world of tournament Bridge, but I also think that this form of Bridge will suit many people. The advantages include: playing with different people, not needing the difficulties of partnership establishment and maintenance, nor the hassle of agreeing on a system and then remembering it.

Queries and explanations in Bridge slow the game down, but it is hard to assign the blame. With that eliminated there is the opportunity to introduce timing, as in chess. Just knowing who is slow will be a good start, before we even think about how to penalise slowness. While it could be done in a simple way, as in chess, another possibility is to automate it. A small computer with a camera (such as a Raspberry Pi), attached to something resembling a floor lamp, could look down on the table and see the play of bidding boxes and cards. This could produce a record of the play, and also record the time taken by each player.

Of course the natural way to start is for existing clubs to give it a try. I think their members will support the experiment if they catch a glimpse of the vision, which is to revitalise the game among younger people. After that we need to figure out how to expand to make it conveniently available to new and existing players.

Monday, August 26, 2024

Positive Communication with Russian and Chinese People

The West is in conflict with the governments of Russia and China, but should be trying to send a message of future peace to the people.

For the Russian people we should be emphasising that we see them as part of our culture, with some of the European world's great novelists, composers, dancers, and also scientists and mathematicians. We don't want the Russian Federation destroyed because Siberia will then inevitably fall under the influence and even control of China. We want to help Russia preserve its unity.

For the Chinese people we seem to be sending the message that we will fight them to preserve the split in their country. The message we should get to them, if we can, is that if their civil war resumes then this time the choice will be between one side that is an economically successful democracy, and the other which is an economically incompetent autocracy that is leading them to conflict and poverty. It can't hurt to get the CCP to consider the possibility that the people might prefer the other side.

We need to win the peace with positive messages for the people.

Sunday, July 14, 2024

Multi-level emergence

"Emergence" is a term for the way a large system with simple rules can give rise to more complex behaviour. Our universe has multiple levels of emergence:

  • We start with the fact that space-time is full of fields. The Higgs field is a scalar, meaning that it is just a number that varies smoothly between points. Other fields are more complex things.
  • From the fields emerge particles: photons, electrons, quarks and more.
  • From the particles emerge a useful collection of atoms.
  • From the atoms emerge a dizzying set of molecules,
  • From some of the atoms, life emerges.
  • From some of the life, intelligent cooperating lifeforms emerge.
  • Also the gravitational field is just right to create stars and planets and other stuff out of the atoms.
  • And nuclear interactions in stars, and when stars explode, is just right to create all those useful atoms.

The scientific solution to this fortuitous situation is backward causation. We're here, so the universe has to be complex enough to create us. We think therefore there has to be a route to thinking.

But this is, however, very unsatisfactory. There are multiple ways that we can go outside of science to guess a solution that doesn't involve backward causation. The traditional one is to postulate a designer, but that breaks Ockham's razor by trying to solve the unlikely complexity by postulating something even harder to explain.

We know our Universe does spontaneous symmetry breaking. The easy way to understand that is to imagine a pencil perfectly balanced on its point. This is an unstable position. The slightest movement of air will make it fall to a stable position on its side, but we can't predict which direction. Another example is that when a liquid gets cold enough it has a lower energy state as a solid, but the order in which molecules join the solid, and hence the shape of the solid, is unpredictable. An example of this in the creation of the Universe is that the Weak Force and Electromagnetism were initially, at high energy, united as one, but they split in a symmetry breaking way.

So my non-science explanation for our amazing multi-level emergent universe is that there are a very large number of universes which are not in causal contact with ours, and hence not amenable to scientific study. Each universe has properties that we can imagine arise in an unpredictable way, like the direction of our falling pencil. Universes with no emergent properties are much more common than those with one level. Universes with one level of emergence are much more common than those with two levels, and so on. And then, there is our unimaginably unlikely and interesting universe. All those universes with less levels of emergence don't have anyone to notice how boring they are.

Which brings us to the title of John Barron's book. We are "The Universe that Discovered Itself".

Wednesday, May 22, 2024

How Interest rates really influence inflation

How do interest rate rises bring down inflation. This is something we never think about since superficially it is obvious: people and businesses have less money to spend, so they buy less, putting downward pressure on prices, and then less stuff is made so unemployment rises which further reduces demand and also puts downward pressure on wages. But is that how it really works?

In most of the Western world central banks have been using interest rates to influence inflation. Also there is a surge in house prices and rental rates. This has led to a lot of discussion in Australia, and probably everywhere, about the "housing crisis". In the course of this we've had two contradictory points.

  • Looking at history, there is a good correlation of higher unemployment with lower house prices and rental rates. And housing costs are a big part of the basket of goods that determine the inflation rate.
  • Yet housing supply is very inelastic. Going from increased demand to higher prices to the building of more houses takes years.

The real link is that there is no shortage of accomodation. If you lose your job then, force majeure, you can't pay the rent or the mortgage. You move back in with your parents or to your brother's garage, or something like that. Quite quickly the supply of rental properties and houses for sale can rise. On the other hand suppose employment is rising, as it did rapidly after the pandemic. Often when people get a job they will want to move, to be closer to the new job, or to widen their romantic opportunities, or just to have more freedom or comfort. Then we saw housing prices rise despite the rising interest rate, and rental rates soar as availability plummeted.

So it turns out that accommodation is quite elastic. Which is lucky because that is the service that is most directly affected by interest rates. If the central bank can get unemployment back where it wants it then the housing crisis will fade away.

However this is a totally unsatisfactory situation. We have one arm of government, Centrelink in Australia, making the life of the unemployed hell, trying to force them to find work, while another arm of government is trying to make sure that work is not available.

I won't make my normal mistake of coming up with a glib solution off the top of my head. But I will say this: When circumstances, such as a pandemic or a drought, have the effect that total production of goods and services is forced to fall, then the government needs to start the uncomfortable conversation of how the burden of reduced income and consumption is to be equitably shared. The current system of slamming the people at the bottom who struggle to keep a job is morally unacceptable.

Monday, May 13, 2024

Climate Change and Energy Policy

Like governments of Left and Right before, the current ALP government in Australia has expressed the obvious fact that we can't move from fossil fuels to wind plus solar plus storage in the necessary time frame. The talk of carbon capture is a fantasy. One reason is that we need baseload power giving "inertia" to the grid, and we need high temperatures for many industrial applications. Nuclear energy covers those bases.

Another reason for nuclear energy is that we are guaranteed to overshoot on carbon emissions, and we are going to need huge amounts of energy to unwind that. Advanced (but not small) nuclear energy is the only plausible route. If fusion doesn't happen then thorium reactors can burn the waste we've got and make fuel continuously from cheap ingredients.

And what good does it do for Australia to go net-zero on wind and solar if most of the world doesn't have that option? It's not as if Australia's actions can protect Australia's climate. We need the world to change,  so we need to make nuclear energy work for the whole world, both for daily energy and even more for the extra energy we need to undo our inevitable overshoot. As a rich technologically advanced country we need to pitch in.

Until a few years ago nobody worried about climate change, except when there was a drought. However commentators and the public are starting to realise that climate change is more about floods than droughts. The fact that air can hold 7% more water for every degree of warming is getting increasing mentions. Of course this is a double edged sword, since it means that if the air is dry, perhaps on the lee side of mountains, then it can suck more moisture out of the ground it passes over. But more often it means that there is more water to fall, and even if it doesn't rain, many plants can get by sucking moisture out of the air. Given that droughts can be worse when they happen, we need to put more engineering effort into buffering the water when it occurs. Understanding aquifers and how to recharge them is a better option than building dams.

Young people are very worried by the lies being spread about the dangers of climate change. Rising sea levels, and many other things, are going to be bad, and we need to fix the problem carefully and energetically, but not rashly. Nobody needs to die. Indeed rash remedies are more likely to kill people than climate change itself.

But then we come to the current crisis, which is the drift towards war. Wars are fought with fossil fuels, and the good guys need to be ahead of that game. More significantly Russia is financing its war with fossil fuel exports. I endorse Doomberg's view (https://newsletter.doomberg.com/p/broken-record-81d): The way to fix that is to ensure that there is a plentiful supply, driving the price down. The effort to slow Russia's exports has created a shortage that is harming economies on our side while increasing Russia's income. Ukraine's attacks on Russia's infrastructure might slow Russia's income, but that will exacerbate the shortages. We need to utilise the resources we've got and fix the climate and other problems later.

Monday, April 1, 2024

Personalised Medicine

The era of personalised medical advice is arriving at last. Australia's new sun guidelines vary the advice by 3 skin types. Well, it's a start.

I enjoy the talks that Dr Paul Mason gives on the LowCarbDownUnder youtube channel, such as the last two:

and
.

Not that I always agree with his theories (such as that the benefit of sunshine is mostly about nitric oxide and that vitamin D is relatively unimportant). But I certainly admire him for taking on the medical establishment which needs shaking up. However we need to get past the current situation where experts shout contradictory views without proper consideration of each other's evidence, and where health advice is hard to change because some important person said something once and we mustn't contradict them.

Returning to the current topic: Dr Mason seems to share the desire of health advisors to give the same advice for everyone. In the second of those two videos he tells us about a plant chemical which is very similar to human cholesterol. He then tells us how most people handle this well and mostly get rid of that chemical without it causing too many problems. However some people incorporate significant amounts of the chemical in places where cholesterol is meant to be, leading to malfunction of the insulin receptors of cells. Yet we don't hear how much of the bad heart statistics from seed oil consumption is because of those people. Maybe he has an alternative diet that is better for everyone, but the advantage might not outweigh other factors for people without the specific problem. He is not slow to claim that other things he opposes have limited benefit.

Skin colour is an obvious case where your origins lead to differences which now affect the best health advice. Here's another.

Suppose your ancestors lived near the sea and ate a lot of seafood. They, and you, probably have a very good system for getting rid of excess salt. And they don't have a working system for retaining salt in case of a future shortage. Now if you wisely decide to stop eating processed food, then you need to get your salt in other ways, and if you don't then you could easily suffer health effects from that.

Now suppose your ancestors lived inland in a low salt area, buying salt when possible. Now their system for getting rid of salt may not work so well. Indeed they may be inclined to retain salt when they get it, despite the resultant health problems. And now you, with those genes, are not well suited for our modern high salt diet.

It is mind-blowing that advice on sun exposure took so long to take skin colour into account. And it still doesn't advise artificial UV for those who can't get enough sun, even though, as Dr Mason would be quick to say, vitamin D tablets don't do the same job. Of course artificial UV is illegal in Victoria, where it is most needed in mainland Australia.

We need to identify more hidden differences that should impact health advice, then develop and fund testing for those differences. In future we might be able to use genetic testing. For the moment we need to look for things that can be tested more cheaply. I expect that this should include the two cases mentioned here: handling salt and handling plant chemicals that imitate cholesterol.

Sunday, January 7, 2024

Mixed strategies in Bridge

BBO (Bridge Base Online) has a lovely system for practicing declarer play. Here is the B-8 problem in level 4:


The suggested solution says "we need to avoid losing 2 club tricks", and suggests leading twice to the KQ. The trouble is that we also need to make 4 tricks in clubs, there being no other likely source of tricks. Leading twice to the KQ fails this extra test when clubs break 4-1, unless East's singleton is the J. So I think it is better to play West for the J and finesse the 10, then return to hand to finesse the 9. On 4-1 breaks this gains when East's singleton is the A, 4, 5, or 6, only losing when it is the J.

[update: It is probably obvious, but to be explicit: The following assumes the plan of leading twice towards KQ of clubs, even though I don't agree that that is the best plan.]

The suggested solution goes on to say (approximately) "If East has Ax of clubs they will duck on the first lead to the K, to give declarer a problem next time. So if East wins the K with the A you should play East for AJ doubleton and just play the Q on the 2nd round." Well that can't be right. If declarer always cashed the Q after the K lost to the A initially, then East would always play the A with Ax so that partner will score their J with Jxx.

So clearly declarer should finesse the 10 on the 2nd round often enough that it is not an easy win for East to play the A with Ax. If both declarer and defender understand all this then each party has an optimal mixed strategy. This is called the Nash Equilibrium. It is simple in this case where each side has 2 options. For each player, both strategies must have the same reward. So I think that means that:

  1. With Ax, East should play the A a third of the time, so that when the A is played it is equally likely to be Ax or AJ.
  2. Declarer should finesse the 10 50% of the time and play the Q 50% of the time.
If either player departs from their equilibrium position then the other can improve their average result. For example if declarer finesses the 10 next less than 50% of the time then East gains by always playing the A with Ax. Or if East plays A from Ax more than a third of the time then declarer gains by always finessing the 10 next.

Of course most such equilibrium solutions are likely to be more complex.

In real life knowledge of opponents and smoothness of play is likely to be the deciding factors, but if you can work out the equilibrium position then you know what mistake you're playing the opponent for.